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?

 

Subscribe to see which companies asked this question

/**
 * 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;
      p=head;
     // head->next=head;
 
       while(p!= NULL)
      {
        //(p->val)++;
        if(p->val==55)
        return true;
        p->val=55;
        p=p->next;
      }
      return false;
    }
};

 

posted @ 2015-11-25 21:07  djiankuo  阅读(139)  评论(0编辑  收藏  举报