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

Linked List Cycle

时间:2014-11-28 16:21:41      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   io   ar   color   sp   for   on   ad   ef   

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

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


#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode {
    int val;
    struct ListNode *next;
 }*ListNode;

bool hasCycle(ListNode *head) {
     ListNode *p1,*p2;
    if(head==NULL||head->next==NULL) return false;
    if(head->next==head) return true;
    for(p1=p2=head;p1!=NULL&&p1->next!=NULL;){
        p1=p1->next;
        p1=p1->next;
        p2=p2->next;
        if(p1==p2) return true;
    }
    return false;
}
 


Linked List Cycle

标签:style   io   ar   color   sp   for   on   ad   ef   

原文地址:http://blog.csdn.net/uj_mosquito/article/details/41576885

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