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

[Linked List]Linked List Cycle,Linked List Cycle II

时间:2015-12-12 12:32:58      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

一.Linked List Cycle
Total Accepted: 85115 Total Submissions: 232388 Difficulty: Medium

 

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 *first =head;
        ListNode *second = head;
        while(first && second)
        {
            first = first->next;
            second = second->next;
            if(second){
                second = second->next;
            }
            if(first==second){
                return true;
            }
        }
        return false;
    }
};
Next challenges: (M) Linked List Cycle II
 
二.Linked List Cycle II
Total Accepted: 61662 Total Submissions: 196038 Difficulty: Medium

 

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

 

[Linked List]Linked List Cycle,Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5041012.html

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