首页 > 其他 > 详细

Linked List Cycle

时间:2014-12-26 20:19:05      阅读:262      评论:0      收藏:0      [点我收藏+]

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==NULL||head->next==NULL)
            return false;
        ListNode *result=new ListNode(0);
        result->next=head;
        ListNode *p,*q;
        p=result;
        q=result;
        
        while(q->next!=NULL&&q->next->next!=NULL)
        {
            q=q->next->next;
            p=p->next;
            if(q==p)
            {
                return true;
            }
           
        }
        
        return false;
    }
};


Linked List Cycle

原文:http://blog.csdn.net/yujin753/article/details/42176149

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!