給定一個鏈表,判斷鏈表中是否有環(huán)。
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環(huán)。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環(huán),其尾部連接到第二個節(jié)點。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
知識點:Set繼承于Collection接口,是一個不允許出現(xiàn)重復元素,并且無序的集合,主要有HashSet和TreeSet兩大實現(xiàn)類。
方法一:新建一個hash表,將每個節(jié)點放入hash表中,如果出現(xiàn)重復,則證明有環(huán)
/**
* 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) {
//Set繼承于Collection接口,是一個不允許出現(xiàn)重復元素,并且無序的集合,主要有HashSet和TreeSet兩大實現(xiàn)類。
Set<ListNode> nodesSeen = new HashSet<>();
while(head!=null)
{
if(nodesSeen.contains(head))
{
return true;
}
else
{
nodesSeen.add(head);
}
head=head.next;
}
return false;
}
}
方法二:雙指針
/**
* 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) {
ListNode slow=head;
ListNode quick=head;
while(slow!=null&&quick!=null&&quick.next!=null)
{
slow=slow.next;
quick=quick.next.next;
if(quick==slow)
{
return true;
}
}
return false;
}
}
因篇幅問題不能全部顯示,請點此查看更多更全內容
Copyright ? 2019- 91gzw.com 版權所有 湘ICP備2023023988號-2
違法及侵權請聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務所王興未律師提供法律服務