题目:
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.
提示:
假设两个链表有合并的情况,那么合并部分的长度一定是一样的,在合并之前长度会有所不同,所以先求出长度,然后把长的链表向前走,让他们“在同一起跑线”,然后依次比较。
代码:
/** * 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 lenA = 0, lenB = 0; ListNode *nodeA, *nodeB; for (nodeA = headA; nodeA; nodeA = nodeA->next, ++lenA); for (nodeB = headB; nodeB; nodeB = nodeB->next, ++lenB); if (lenB > lenA) { for (int i = 0; i < lenB - lenA; ++i, headB = headB->next); } else { for (int i = 0; i < lenA - lenB; ++i, headA = headA->next); } if (headA == headB) return headA; while (headA && headB) { headA = headA->next; headB = headB->next; if (headA == headB) return headA; } return NULL; } };
时间: 2024-10-10 13:40:04