題目描述
給定一個鏈表,判斷鏈表中是否有環。
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
代碼及解題思路
/**
* 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) {
/**
* 構造一個fast指針,一個slow指針。
* fast指針走兩步,slow走一步,他們總會遇到的。
**/
if(head==null || head.next==null){
return false;
}
int num=0;
ListNode first,second=head;
/*first初始化時比second快*/
first=head.next.next;
second=head.next;
while(first!=second){
//如果first或者first下一步爲空的話,說明不是環形鏈表
if(first==null || first.next==null){
return false;
}
second=second.next;
first=first.next.next;
}
return true;
}
}
總結
不是所有的鏈表都需要創建一個頭結點的,當然創建了也沒有錯。