标签:
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?
题意:判断一个链表中是否存在环。
思路:(参考别人的做法)采用“快慢指针”检查链表是否含有环。即让一个指针一次走一步,另一个指针一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。
代码:
public boolean hasCycle(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast!=null&&fast.next!=null){ slow = slow.next; fast = fast.next.next; if(slow==fast) return true; } return false; }
LeetCode(141): Linked List Cycle
标签:
原文地址:http://www.cnblogs.com/Lewisr/p/5134493.html