LeetCode:Linked List Cycle I & II

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;
      }
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值