[Leetcode]Intersection of Two Linked Lists
来源:互联网 发布:python 计算macd 编辑:程序博客网 时间:2024/05/21 10:51
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.
根据上述性质,如果两个链表等长,那么只要两个链表指针匀速向后移动,当两个指针第一次相等时就找到了交集开始的元素。
如果两个链表不等长,就去掉较长链表多出来的部分,使链表等长,然后再进行上述步骤。(因为交集不可能从多出来的部分开始)
如果两个链表最后一个元素指针也不同,则证明两个链表没有交集。所以,我在求链表长度的方法里加了一个返回值,用pair类型同时返回了链表长度和链表最后一个元素指针,如果最后一个元素指针都不同,就直接返回NULL,不再进行下面的步骤了。
中间还用到一些指针引用神马的,自觉写的还是比较优雅的,请大家多多提出意见~~~
class Solution {public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if (NULL == headA || NULL == headB) return NULL;ListNode *tmpA = headA,*tmpB = headB;pair<int, ListNode *> pairA = calLength(headA);pair<int, ListNode *> pairB = calLength(headB);int lengthA = pairA.first;int lengthB = pairB.first;ListNode *lastA = pairA.second;ListNode *lastB = pairB.second;if (lastA != lastB) return NULL;ListNode *&longList = lengthA >= lengthB ? tmpA : tmpB;ListNode *&shortList = lengthA >= lengthB ? tmpB : tmpA;for (int i = 0; i < abs(lengthA - lengthB); i++){longList = longList->next;}while (NULL != longList && NULL != shortList){if (longList == shortList){return longList;}longList = longList->next;shortList = shortList->next;}return NULL;}pair<int,ListNode *> calLength(ListNode *root){ListNode *tmp = root;int length = 1;while (tmp->next != NULL){length++;tmp = tmp->next;}return pair<int, ListNode *>(length,tmp);}};
1 0
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- ios 真机调试时出现CopyPngFile error解决方法
- Oracle查询表空间使用情况
- Linux的watch命令 — 实时监测命令的运行结果
- 人见人爱A-B
- iOS App性能优化
- [Leetcode]Intersection of Two Linked Lists
- C++中const使用总结
- 中介者模式
- SQL 语句中的通配符
- 单线程模型中Message、Handler、MessageQueue、Looper之间的关系
- FZU - 2107 Hua Rong Dao
- enum与typedef enum的用法
- Duilib学习笔记《01》— duilib整体框架认识
- QML类型