LeetCode 141. Linked List Cycle
来源:互联网 发布:淘宝链接里面的scm 编辑:程序博客网 时间:2024/06/12 00:17
题目链接
141. 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?
满足 without using extra space这个要求的话,可以只用2个指针来判断一个链表中的环,快的指针一次走2个结点,慢指针一次走一个结点,若有环路,两指针会先后进入环路,在慢指针被快指针“扣圈”时两指针在环路上相遇,代码:
/** * 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* faster, *slower; if (head == NULL) return false; faster = slower = head; while (true) { slower = slower->next; faster = faster->next; if (faster == NULL) return false; faster = faster->next; if (faster == NULL) return false; if (slower == faster) return true; } }};
阅读全文