Leetcode 第142題:Linked List Cycle II-- 環形鏈表Ⅱ(C++、Python)

題目地址:Linked List Cycle II


題目簡介:

給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。

說明:不允許修改給定的鏈表。

示例 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

示例 2:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.


題目解析:

1、暴力

如果有環,那麼將從第二次進入環時,開頭以及被遍歷了。那麼只需記住每個遍歷的節點,遍歷之前查找是否遍歷過了即可。

C++版:

/**
 * 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) {
        ListNode *temp = head;
        vector<ListNode*> store;
        while(temp)
        {
            if (find(store.begin(), store.end(), temp) == store.end())
            {
                store.push_back(temp);
                temp = temp -> next;
            }
            else
                return temp;
        }
        return NULL;
    }
};
static auto x = []() { std::ios::sync_with_stdio(false);std::cin.tie(nullptr);return 0;}();

Python版:

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        temp = head
        store = []
        while(temp != None):
            if temp not in store:
                store.append(temp)
                temp = temp.next
            else:
                return temp
        return None

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章