<leetcode系列> Linked List Cycle

来源:互联网 发布:数据决策分析系统 编辑:程序博客网 时间:2024/06/05 01:19

Linked List Cycle

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

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

题目意思: 给定一个链表, 判断里面是否含有环.

原题链接: https://leetcode.com/problems/linked-list-cycle/

这是一个典型的运用快指针和慢指针的题目.快慢指针是指移动步长不一样,快指针每次移动的步长要大一些,慢指针每次移动的步长要小一些.

如果链表没有环,则最后必然会有尾节点,就如同两个人在操场跑步, 快指针会第一个冲过终点(NULL).

如果链表有环,则跑的快的人,必然会在某个时候再次遇到跑的慢的人,这个时候跑的快的人正好在环里超过跑得慢的那个人1圈或n圈.

代码如下:

bool hasCycle(struct ListNode *head) {    if ((NULL == head) || (NULL == head->next)) {        return false;    }    int slowStep = 1;    int fastStep = 2;    struct ListNode* slow = head;    struct ListNode* fast = head;    while (true) {        for (int j = 0; j < fastStep; ++j) {            fast = fast->next;            if (NULL == fast) {                return false;            }            if (fast == slow) {                return true;            }        }        for (int i = 0; i < slowStep; ++i) {            slow = slow->next;        }    }}
0 0
原创粉丝点击