leetcode 141. Linked List Cycle

来源:互联网 发布:mac sunlime3 注册码 编辑:程序博客网 时间:2024/05/22 09:06

题目描述:

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

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

解题思路:

这道题比较简单,用两个指针就可以了。

/** * 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 == 0 || head -> next == 0)            return false;        ListNode *fir = head -> next, *sec = head -> next -> next;        while(sec != 0 && fir != sec){            fir = fir -> next;            sec = sec -> next;            if(sec)                sec = sec -> next;            else                break;        }        return sec == fir;    }};

另附上leetcode上的题解,上面有对对算法的时空复杂度进行分析,而且也给出了空间复杂度为O(n)和O(1)的两种算法。

1 0
原创粉丝点击