160. Intersection of Two Linked Lists(Linked List)

来源:互联网 发布:明星代言页游 知乎 编辑:程序博客网 时间:2024/06/03 17:29

Title

Write a program to find the node at which the intersection of two singly linked lists begins.

an example

Notes:If the two linked lists have no intersection at all, return null.The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory.

Language C

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {    if(headA==NULL || headB == NULL){        return NULL;    }    struct ListNode *p, *q, *a, *b;    p = headA;    a = headA;    q = headB;    b = headB;    while(p!=NULL && q!=NULL){        p = p->next;        q = q->next;    }    while(p != NULL){        a = a->next;        p = p->next;    }    while(q != NULL){        b = b->next;        q = q->next;    }    while(a!=NULL && b!=NULL){        if(a == b){            return a;        }        a = a->next;        b = b->next;    }    return NULL;}

runtime:37ms

思路:

首先,这个题目是判断两个单链表是否有交叉,如何寻找交叉节点问题

指针p、q分别遍历链表a、b,假设q先到达NULL(即 假设a 比 b 长),此时从a的头发出一个指针t,当p到达NULL时,从b的头发出s,当s==t的时候即交点。

虽然基础,但这个我也是需要借鉴的…至于思路,我就看了下知乎这里,谢谢。

0 0
原创粉丝点击