利用两个栈,然后分别存储每一个链表。
继而,相继pop相同的节点。
有些细节需要注意,请看最后的返回值是如何处理的。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 #define MAX 100000
 typedef struct Stack{
     struct ListNode *array[MAX];
     int top;
 }Stack;
 struct ListNode *get_top(Stack s){
     return s.array[s.top-1];
 }
 struct ListNode *pop(Stack *s){
     return s->array[--(s->top)];
 }
 void push(Stack *s,struct ListNode *p){
     s->array[s->top++]=p;
 }
 int empty(Stack s){
     return(s.top==0);
 }
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    Stack s1,s2;
    struct ListNode *p;
    
    s1.top=0,s2.top=0;
    p=headA;
    while(p!=NULL){
        push(&s1,p);
        p=p->next;
    }
    p=headB;
    while(p!=NULL){
        push(&s2,p);
        p=p->next;
    }
    while(!empty(s1)&&!empty(s2)){
        if(get_top(s1)==get_top(s2))
        {
            pop(&s1);
            pop(&s2);
        }
        else break;
    }
    if(headA||headB){
        if(!empty(s1))return (get_top(s1)->next);
         else if(!empty(s2))return  get_top(s2)->next;
            else return headA;
    }
    return NULL;//两个链表都为空的话返回NULL
}
自己写的栈结构,所以代码有点长。
Any problems contact me.
Intersection of Two Linked Lists | LeetCode
原文:http://www.cnblogs.com/ProtectedDream/p/4542911.html