LeetCode 160. 相交链表(Intersection of Two Linked Lists)
编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
在节点 c1 开始相交。
注意:
- 如果两个链表没有交点,返回
null. - 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
- 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
解题思路
首先分别获得两个链表的长度,然后让较长的链表先走两个长度的差值,使得两链表尾部对齐。然后两个链表再同时向后移动,并比较节点是否相等。
代码
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 int getLength(ListNode *head){
12 int len = 0;
13 ListNode *node = head;
14 while(node){
15 len++;
16 node = node->next;
17 }
18 return len;
19 }
20 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
21 int lenA = getLength(headA), lenB = getLength(headB);
22 if(lenA < lenB) return getIntersectionNode(headB, headA);
23 int p = lenA - lenB;
24 ListNode *nodeA = headA, *nodeB = headB;
25 while(p){
26 nodeA = nodeA->next;
27 p--;
28 }
29 while(nodeA){
30 if(nodeA == nodeB) break;
31 nodeA = nodeA->next;
32 nodeB = nodeB->next;
33 }
34 return nodeA;
35 }
36 };


浙公网安备 33010602011771号