160. Intersection of Two Linked Lists
来源:互联网 发布:萤火虫之墓影评知乎 编辑:程序博客网 时间:2024/06/01 14:24
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.
找两个链表的交叉点。
如果两个链表相等,同时从头结点开始遍历,直到交叉节点(如果有)
如果两个链表不相等,那么就要先让长的遍历,遍历的次数是长的减短的,比如上述为6-5=1
则让b先遍历一个,然后a从头结点开始遍历,b从第二个节点b2开始遍历知道相遇(如果有)
这里可以使用一个环来简化。以下是一个比较简单明了的方法,值得借鉴,源自于LeetCode
/** * 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) { ListNode *temp1=headA, *temp2=headB; while(temp1!=temp2){ temp1=temp1?temp1->next:headB; temp2=temp2?temp2->next:headA; } return temp1; }};
阅读全文
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
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 160. Intersection of Two Linked Lists
- 使用高效字节流拷贝文件夹
- HDU 6134 Battlestation Operational(莫比乌斯反演+线性筛)
- HDU 6152 2017中国大学生程序设计大赛网络赛 1003
- 构建ubuntu根文件系统
- UltraISO制作U盘系统盘安装CentOS经验分享
- 160. Intersection of Two Linked Lists
- 【JavaSE笔记】多线程(一)进程&线程&Thread&同步代码块
- 解决html页面插入中文数据到mysql数据库出现乱码的情况。
- 【Jiya&Chieng】(贰)CoreDump —— 崩溃前的自拍
- mysql 调优学习笔记
- 英语考试
- struts-配置struts
- 最短路入门-- hd 2544【floyed+dijsktra】
- JAVA向上转型,构造函数