Given a linked list, determine if it has a cycle in it.
解题:
判断单链表是否具有环,使用两个指针once和twice遍历链表,once一次走一步,twice一次走两步,如果相遇,则说明有环,否则没有。
原因是,如果单链表具有环,不论once和twice进入环的位置如何,由于twice每次比once多走一步,类似操场跑步,twice最终会追上once。
代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 bool hasCycle(ListNode *head) { 12 if (head == NULL || head->next == NULL) 13 return false; 14 ListNode* once = head->next; 15 ListNode* twice = head->next->next; 16 17 while (once && twice && twice->next) { 18 if (once == twice) 19 return true; 20 once = once->next; 21 twice = twice->next->next; 22 } 23 24 return false; 25 } 26 };