[LeetCode 第10题] -- Linked List Cycle

来源:互联网 发布:php curl模拟表单提交 编辑:程序博客网 时间:2024/06/10 20:38


题目链接: linked List 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);};bool Solution::hasCycle (ListNode *head) {    if (NULL == head) {        return false;    }    ListNode *tmpHeadOne = head;    ListNode *tmpHeadTwo = head;    int step = 0;    while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {        if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {            return true;        }        step++;        tmpHeadOne = tmpHeadOne->next;        tmpHeadTwo = tmpHeadTwo->next;        if (tmpHeadTwo != NULL) {            tmpHeadTwo = tmpHeadTwo->next;        }    }    return false;}


0 0
原创粉丝点击