mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 160. Intersection of Two Linked Lists.md
This commit is contained in:
parent
29948916be
commit
89ca6c5c77
52
160. Intersection of Two Linked Lists.md
Normal file
52
160. Intersection of Two Linked Lists.md
Normal file
@ -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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user