LeetCode/solutions/160. Intersection of Two Linked Lists.md

53 lines
1.6 KiB
Markdown
Raw Permalink Normal View History

# [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++
2019-09-13 15:08:41 +00:00
``` 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;
}
};
```