diff --git a/160. Intersection of Two Linked Lists.md b/160. Intersection of Two Linked Lists.md new file mode 100644 index 0000000..5743db3 --- /dev/null +++ b/160. Intersection of Two Linked Lists.md @@ -0,0 +1,52 @@ +# [160. Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/description/) +# 思路 +题目要求求两个链表的交集,需要注意的事实是只要两个链表有一个节点重合了,那么其后的节点也是重合的,这个节点也即所求,就如题图c1所示。 +先计算两个链表的长度差delta_len,然后设置两个工作指针p1和p2,保证p1所在的链表是较短的链表, 再让p2先往后移动delta_len步,最后p1、p2同时往后移动 +直到p1 == p2即到达所求节点c1或者遇到NULL。 +时间复杂度O(n), 空间复杂度O(1) +# C++ +``` +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if(!(headA && headB)) return NULL; + int delta_len = 0; + ListNode *p1 = headA, *p2 = headB, *tmp = NULL; + while(p1 && p2){ + p1 = p1 -> next; + p2 = p2 -> next; + } + if(p1) tmp = p1; + else tmp = p2; + while(tmp){ + delta_len++; + tmp = tmp -> next; + } + //以上代码求链表长度差 + + if(p1){ // 保证p1长度不大于p2 + p1 = headB; + p2 = headA; + } + else{ + p1 = headA; + p2 = headB; + } + + while(delta_len--) p2 = p2 -> next; + while(p1 && p1 != p2){ + p1 = p1 -> next; + p2 = p2 -> next; + } + return p1; + } +}; +```