LeetCode演算法題141:環形連結串列解析
阿新 • • 發佈:2018-11-11
給定一個連結串列,判斷連結串列中是否有環。
進階:
你能否不使用額外空間解決此題?
這個題如果是常規思路的話就是選擇一個容器來儲存所有遍歷過的連結串列節點,然後檢測下一個是否已經存在在容器中,考慮到需要使用有find方法的容器,這裡就使用set來儲存。C++程式碼就是這樣的思路,然後python程式碼使用了另外的思路,這個思路的空間複雜度更低,時間複雜度會提高一些,這個思路就是設定兩個指標來遍歷連結串列,一快一慢,如果有環,那麼總會有快的追上慢的(被套圈),否則快的遍歷到了空指標,則一定沒有環。
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 *> nodes;
ListNode *p = head;
while(p!=NULL){
if(nodes.find(p)!=nodes.end()) return true;
else{
nodes.insert(p);
p = p->next;
}
}
return false;
}
};
python3原始碼:
# 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
"""
if head==None or head.next==None:
return False
pSlow = head
pFast = head.next
while pFast!=None and pFast.next!=None:
if pSlow==pFast:
return True
pSlow = pSlow.next
pFast = pFast.next.next
return False