您的位置:首页 > 其它

LeetCode 160 Intersection of Two Linked Lists

2017-09-13 15:24 357 查看
题目:

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

For example, the following two linked lists:
A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3


begin to intersect at node c1.

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.
题目链接
题意:

给出了两个单列表,要求找到两个单列表第一个交叉的节点。

有四点要求:

如果没有交叉,则返回NULL。
不得更改链表结构。
不存在环结构。
代码时间复杂度为O(n), 空间复杂度为O(1)。
第一次写没有看清要求,直接map统计记录后输出,代码如下:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
map<ListNode*, int> dic;
while (headA) {
dic[headA] ++;
headA = headA->next;
}
while (headB) {
dic[headB] ++;
if (dic[headB] == 2)
return headB;
headB = headB->next;
}
return NULL;
}
};
这种的空间复杂度一定不是O(1),所以又想了一种办法。
先定义两个指针分别指向两个链表的首节点,两个变量统计两个链表的长度,然后分别遍历一遍统计长度,将指向长度较长的那个指针指向到某一结点使得从此节点开始的剩余长度与短的链表长度相同。之后分别从两个指针所指向的位置开始遍历,返回第一个相同的节点,假如没有,则返回NULL。
代码如下:

class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *A, *B;
A = headA;
B = headB;
int lenA = 0, lenB = 0;
while (A) {
lenA ++;
A = A->next;
}
while (B) {
lenB ++;
B = B->next;
}
A = headA;
B = headB;
if (lenA > lenB) {
while (lenA > lenB) {
A = A->next;
lenA --;
}
}
else {
while (lenB > lenA) {
B = B->next;
lenB --;
}
}
while (A) {
if (A == B) return A;
A = A->next;
B = B->next;
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: