Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断链表是否有环,经典的做法就是设快慢指针各一个,当快指针和慢指针重合时说明链接有环,否则快指针将为null。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)return false;
if(head.next==null)return false;
ListNode slow=head,fast=head.next;
while(slow!=fast)
{
if(slow==null || fast==null || fast.next==null)return false;
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.
这个问题是第一个问题的继续,如果链表有环,快指针”套圈“慢指针时候,快慢指针必然在环上,环的开始节点的特性是必然有两个不同的node的next指向环的开头(链表不能刚好就是一个环,得有条”尾巴“),慢指针等于快指针的next,以快指针所在Node为标记点(快指针不动),慢指针继续在环上遍历直至再次遇到快指针,慢指针没走一次,从头设置一个p对整个链接进行遍历,如果p!=slow,但是p.next==slow.next;说明其共同的next为环的起点。当满指针继续追到快指针的地方,还没有找到起点,说明整个链接就是一个环,这时候返回head.
/**
* 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;
if(head.next==null)return null;
if(head.next==head)return head;
ListNode slow=head,fast=head.next,p;
while(slow!=fast)
{
if(slow==null || fast==null || fast.next==null)return null;
slow=slow.next;
fast=fast.next.next;
}
slow=fast.next;
while(slow!=fast)
{ p=head;
while(p!=fast){
if(p.next==slow.next && p!=slow)return p.next;
p=p.next;
}
slow=slow.next;
}
return head;
}
}