LeetCode 141. Linked List Cycle

来源:互联网 发布:ubuntu 14.04 glib 编辑:程序博客网 时间:2024/05/22 00:11

141. Linked List Cycle

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

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

Analysis
这道题目的意思就是判断链表中是否存在环。
我的做法是利用两个指针。其实觉得这道题需要用数学来推算。
具体是一个指针每一跳一步,另一个指针每一次跳两步。
如果链表中存在着环,则这两个指针一定会相遇。

Code

/** * 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 == NULL) return false ;        ListNode * first = head;        ListNode * second = head;        while(first!=NULL&&first->next!=NULL){                      second = second->next;            first = first->next->next;            if(first == second){                return true;            }        }        return false;    }};
0 0