码迷,mamicode.com
首页 > 其他好文 > 详细

判断链表是否有环

时间:2014-10-23 00:03:10      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:链表   指针   c   校园招聘   

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

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

关键点:1)判断链表是否有环。

2)一个小坑在判断root和root的next是否为空上。

3)可以看为追及问题。最关键的坑在判断快走(每次走2步的节点),走1步会不会已经走到头。。。


/**

 * 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) {
        stack<ListNode*>    stk;
        ListNode    *nodeA,*nodeB;
        if(NULL ==  head||NULL  ==  head->next)
        {
            return  false;
        }
        nodeA   =   head;
        nodeB   =   head;
        while(NULL!=(nodeB->next->next))
        {
            nodeA=nodeA->next;
            nodeB=nodeB->next->next;
            if(nodeA    ==  nodeB)
                return  true;
            if(NULL ==  nodeB->next)
                return  false;
        }
        return  false;
    }
};

判断链表是否有环

标签:链表   指针   c   校园招聘   

原文地址:http://blog.csdn.net/shahongzhou/article/details/40385775

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!