设为首页 加入收藏

TOP

[LeetCode] Linked List Cycle
2015-11-21 01:00:34 来源: 作者: 【 】 浏览:2
Tags:LeetCode Linked List Cycle

?

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?

解题思路:

1、最基本的办法是用一个set来存储所有已经出现过的指针。若出现重复,则表示有环,若没有重复,则没有环。

?

/**
 * 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* p = head;
        set
  
    s;
        while(p!=NULL){
            if(s.find(p)!=s.end()){
                return true;
            }
            s.insert(p);
            p=p->next;
        }
        return false;
    }
};
  
2、双指针方法。设立两个指针,一个指针每次走一步,另外一个指针每次走两步。若两个指针相遇,表示有环。不相遇,则表示无环。具体见:http://blog.csdn.net/kangrydotnet/article/details/45154927

?

?

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



?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LightOJ 1356 Prime Independence.. 下一篇zoj 3870 异或运算

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: