leetcode Linked List Cycle II
来源:互联网 发布:手机建筑图纸软件 编辑:程序博客网 时间:2024/06/08 10:03
题目链接
思想:
首先判断是不是有圈
如果有圈的话可以找两个列表的第一个公共节点。这两个链表分别是
head->……->tail
tail->….tail
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head==null) { return null; } ListNode pre=head; ListNode tail=head; while(true) { if(pre!=null&&pre.next!=null) { pre=pre.next.next; tail=tail.next; } else { break; } if(pre==tail) { return getIntersectionNode(pre,head); } } return null; } public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode temp; //求长度 int linkALength=0; temp=headA; while(temp!=headA) { temp=temp.next; linkALength++; } int linkBLength=0; temp=headB; while(temp!=headB) { temp=temp.next; linkBLength++; } //对齐 ListNode linkA=headA; ListNode linkB=headB; if(linkALength>linkBLength) { for(int i=0;i<linkALength-linkBLength;i++) { linkA=linkA.next; } } else { for(int i=0;i<linkBLength-linkALength;i++) { linkB=linkB.next; } } while(linkA!=null&&linkB!=null) { if(linkA==linkB) { return linkA; } linkA=linkA.next; linkB=linkB.next; } return null; }}
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Python Unitest 源码阅读:概述
- voltDB 查询语句解析过程 初步分析
- sql语句中where、group by、having、order by 是否可以使用别名
- 关于C++中的显示调用explicit
- mysql常用语句
- leetcode Linked List Cycle II
- Android Fragment嵌套
- Selenium 使用方法小结
- iOS thread1:exc_bad)access(code=exc_1386_gpflt) 调试方案
- codeforces 10C C. Digital Root(数论)
- Spring 3 MVC深入研究
- testlink安装全攻略
- Xilinx Spartan 6 驱动ADS1278/4
- MySQL字符集