LeetCode-160. Intersection of Two Linked Lists
来源:互联网 发布:三国志9高难度优化伴侣 编辑:程序博客网 时间:2024/06/05 04:25
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.
思路:
1、从表尾往前看,可以看出链表在相交以后的节点值和节点数目都相同,不同的地方在于未相交前时两链表的节点数目,所以我们可以遍历两个链表记录下每个链表的长度。
2、用两个指针分别指向两链表的表头,节点数目多的链表指针先走n歩后,n为两链表的节点数目之差,节点数目少的链表再走
3、在这个过程中,只要找到相同的节点就找到了交汇处,如果直到表尾都没有找到则说明两链表没有交汇,返回null。
/** * 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) { int lengthOfListA=getLengthOfList(headA); int lengthOfListB=getLengthOfList(headB); ListNode* pA=headA; ListNode* pB=headB; if(lengthOfListA>lengthOfListB) { int plusLength=lengthOfListA-lengthOfListB; for(int i=0;i<plusLength;++i) { pA=pA->next; } } else if(lengthOfListA<lengthOfListB) { int plusLength=lengthOfListB-lengthOfListA; for(int i=0;i<plusLength;++i) { pB=pB->next; } } while(pA&&pB) { if(pA->val==pB->val) return pA; pA=pA->next; pB=pB->next; } return NULL; } int getLengthOfList(ListNode* head) { int length=0; while(head!=nullptr) { length++; head=head->next; } return length; }};
阅读全文
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode 160. Intersection of Two Linked Lists
- 160.[Leetcode]Intersection of Two Linked Lists
- 《计算机操作系统》总结二(进程与线程)
- 11.14学习心得
- freeswitch 在redhat 7.0/centos 7.0上的编译安装
- C#字符串转数组,数组转字符串,后遍历数组
- 关于IOS证书过期的问题
- LeetCode-160. Intersection of Two Linked Lists
- C语言之指针*p++和*(p++)区别
- on release of batch it still contained JDBC statements
- Paxos算法
- 基于EasyNVR二次开发实现业务需求:用户、权限、设备管理
- dajngo debug=false时无法加载css、js
- UE4 坐标轴绘制
- 20171114
- Android:学习AIDL,这一篇文章就够了(上)