您的位置:首页 > 其它

leetcode141~Linked List Cycle

2017-03-24 08:47 387 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

解决链表问题的经典做法:使用俩指针fast和slow,判断最后fast是为null还是fast==slow即可。

public class LinkedListCycle {
/*
* 思路:使用 两个指针slow和fast 看最后有没有相遇
*/
public boolean hasCycle2(ListNode head) {
if(head==null) return false;
ListNode slow = head;
ListNode fast = head;
boolean flag = false;
while(fast!=null && fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
flag = true;
break;
}
}
return flag;
}

public boolean hasCycle(ListNode head) {
if(head==null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow!=fast) {
if(fast==null || fast.next==null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: