[LeetCode] Linked List Cycle

来源:互联网 发布:阿斯顿马丁广告 知乎 编辑:程序博客网 时间:2024/06/06 01:49

题目:

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) {        ListNode *fast = head;        ListNode *slow = head;                if(head == NULL || head -> next == NULL || head -> next -> next == NULL) {            return false;        }        else {            while(fast != NULL && fast -> next != NULL) {                fast = fast -> next -> next;                slow = slow -> next;                            if(fast == slow) {                    return true;                }            }            return false;        }    }};

经典算法:快慢指针判断链表是否有环,快指针每次前进两步,慢指针每次前进一步,如果有环,则快慢指针必定在某一时刻相遇;如果没有环,则快指针先到达链表结尾。

0 0
原创粉丝点击