1. 程式人生 > >資料結構之連結串列 給定一個連結串列,判斷連結串列中是否有環。

資料結構之連結串列 給定一個連結串列,判斷連結串列中是否有環。

給定一個連結串列,判斷連結串列中是否有環。

為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環

 

 

/**
 * 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; } ListNode fast = head;//一次兩步 ListNode slow = head;//一次一步 if (fast.next != null){ fast = fast.next.next; }else {
return false; } slow = slow.next; // find the first meet, or null while(fast != slow){ if(fast != null && fast.next != null){ fast = fast.next.next; } else{ return false; } slow = slow.next; }
return true; } }