题目链接: 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; }
时间: 2024-10-28 14:47:22