Intersection of Two Linked Lists
来源:互联网 发布:ubuntu根目录空间不足 编辑:程序博客网 时间:2024/05/16 11:16
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.
这道题也参考了下思路, 主要的问题在于怎么转化成linked list cycle问题,如果两个链表有公共部分,那么将两个链表链接起来以后会形成环, 这样就可以根据上一题的思路来解。
但是要注意将链表恢复。这个思路要再梳理一下。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){ return null; } ListNode pointer = headA; ListNode breakPoint; while(pointer.next != null){ pointer = pointer.next; } breakPoint = pointer; pointer.next = headB; ListNode slow = headA; ListNode fast = headA; while(fast.next!=null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ //根据公式,快指针到重合点的举例==head到重合点的距离 slow = headA; while(slow!= fast){ slow = slow.next; fast = fast.next; } breakPoint.next = null; return slow; } } breakPoint.next = null; return null; }
sdfsd
0 0
- 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
- 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
- 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
- corbova build android时gradle错误
- jdk下常用文件夹
- 暴露敏感数据
- 最新消息,马云在杭州开了一家惊艳世界的动物园!
- mysql
- Intersection of Two Linked Lists
- matlab 3个子窗口一个主窗口 选择显示
- HDU-1875-畅通工程再续
- GUI界面编程——记事本初级实现
- matlab 去掉参数空白
- matlab 设置参数 和参数值
- matlab 6个参数,各个策略使用参数个数不同,显示
- 游戏-功能测试(一)
- Linked List Random Node