[leetcode] 141. Linked List Cycle

来源:互联网 发布:linux系统下载iso mac 编辑:程序博客网 时间:2024/05/19 08:04

Question:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Solution:

很有趣的一道题。要求使用O(1)的空间复杂度。主要思路是对于访问过的节点,都把指向下一个节点的指针指向head,然后跳到原本的下一个节点继续访问。这样,如果有环,就会在某个时刻跳回到一个已访问的节点,然后访问该节点的下一个节点,就会访问到head,于是检测到右环。

/** * 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) {        if (!head || !head->next)            return false;        ListNode *tmp = head->next, *t;        while (tmp) {            if (tmp == head)                return true;            t = tmp->next;            tmp->next = head;            tmp = t;        }        return false;    }};
原创粉丝点击