力扣题-10.19
力扣题1:141. 环形链表
解题思想:将遍历过的链表进行记录即可
# 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:
return False
node_list = []
temp = head
while temp.next!=None:
if temp in node_list:
return True
else:
node_list.append(temp)
temp = temp.next
return False
/**
* 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) {
unordered_set<ListNode*> node_list;
if(head==nullptr){
return false;
}
ListNode * temp = head;
while(temp->next!=nullptr){
if(node_list.count(temp)){
return true;
}
else{
node_list.insert(temp);
}
temp = temp->next;
}
return false;
}
};
力扣题2:142. 环形链表 II
解题思想:同上一题一样,只是返回的结果不同
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return
node_list = []
temp = head
while temp.next!=None:
if temp in node_list:
return temp
else:
node_list.append(temp)
temp = temp.next
return
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> node_list;
if(head==nullptr){
return NULL;
}
ListNode * temp = head;
while(temp->next!=nullptr){
if(node_list.count(temp)){
return temp;
}
else{
node_list.insert(temp);
}
temp = temp->next;
}
return NULL;
}
};