4.24 leetcode -24 linked-list-cycle

来源:互联网 发布:网络调研公司排名 编辑:程序博客网 时间:2024/06/05 02:02
题目描述

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

给一个链表,看是否有循环,不用额外控件,一个一步走,一个两步走,能汇合就有cycle

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


原创粉丝点击