leetCode--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?


解題思路:利用快慢指針的性質,快慢指針相遇說明單鏈表中存在環



  class ListNode {
      int val;
     ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null)return false;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow)return true;
        }
        return false;
        
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章