141循環リンクリスト
Leetcode:https://leetcode-cn.com/problems/linked-list-cycle/
リストを指定すると、リストがリングかどうかが決定されます。
リングを与えられたリストを表示するために、我々は、POS整数(インデックスは0から始まる)リストの位置を表すために、リストの最後に接続されています。posが-1の場合、リングがこのリストに含まれていません。
答え
図に示すように、2つのケースが、ありますが、そこにチェーンリングのAです。
思考
トラバースに二時間を設定します
何の残業がない場合は何のリング、またはNULLがない場合は、リングがあり、NULLが存在するかどうかを確認するために、トラバースされています
アイデア2
各横断時間は、アドレスが抑えされ、その後、現在のアドレスが前に現れたかどうかを判断
C ++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> buf;
ListNode* cur = head;
while(cur && cur->next) {
if(buf.find(cur) != buf.end())
return true;
buf.insert(cur);
cur = cur->next;
}
return false;
}
};
パイソン
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
cur = head
buf = set()
while cur and cur.next:
buf.add(cur)
if cur.next in buf:
return True
cur = cur.next
return False
三つのアイデア
スピードウェイポインタ
C ++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(slow && fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
パイソン
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False