leetcode160~Intersection of Two Linked Lists
来源:互联网 发布:mac 扩展磁盘 找不到 编辑:程序博客网 时间:2024/05/20 01:12
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.
public class IntersectionofTwoLinkedLists { /* * 统计两个链表的长度,然后使用俩指针,让长链表的指针先走lenA-lenB步,然后再一起走 */ public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { if(headA==null || headB==null) return null; int lenA = getLength(headA); int lenB = getLength(headB); //长链表先走len1-len2步 while(lenA>lenB) { headA = headA.next; lenA--; } while(lenA<lenB) { headB = headB.next; lenB--; } //同时遍历 while(headA!=headB) { headA = headA.next; headB = headB.next; } return headA; } private int getLength(ListNode head) { int len = 0; while(head!=null) { head = head.next; len++; } return len; } //一个链表遍历到尾部时,从另外一个链表的头部开始再次遍历,最终会相遇 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null || headB==null) return null; ListNode curA = headA; ListNode curB = headB; while(curA!=curB) { curA = curA==null? headB:curA.next; curB = curB==null? headA:curB.next; } return curA; }}
0 0
- [leetcode160链表]Intersection of Two Linked Lists
- Leetcode160-Intersection of Two Linked Lists
- [LeetCode160] Intersection of Two Linked Lists
- leetcode160---Intersection of Two Linked Lists(交叉点)
- LeetCode160. Intersection of Two Linked Lists
- 【Leetcode160】. Intersection of Two Linked Lists-题解
- LeetCode160. Intersection of Two Linked Lists
- leetcode160~Intersection of Two Linked Lists
- leetcode160. Intersection of Two Linked Lists
- leetcode160-Intersection of Two Linked Lists
- LeetCode160. Intersection of Two Linked Lists
- Leetcode160. Intersection of Two Linked Lists/C++
- LeetCode160——Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- 扫描器与集合框架
- Android 根据消息推送内容跳转至指定页面(极光推送)
- [leetcode]279. Perfect Squares
- 关于c++中的cin
- opencv读取视频
- leetcode160~Intersection of Two Linked Lists
- 学习淘淘商城第八课(SSM框架整合之Dao层整合)
- 2017本科组模拟赛(计算生日)
- hibernate 使用实体 和附加类 作为属性
- 从map中取值的正确方法
- 展翅翱翔之时 (はばたきのとき)
- IDEA中多行注释及取消注释快捷键
- 【转】Python 包管理工具解惑【原文:http://zengrong.net/post/2169.htm】
- Android实用功能分享——应用版本的更新实例