题目大意:给一个链表,判断是否存在循环,最好不要使用额外空间code
思路:定义一个假节点fakeNext,遍历这个链表,判断该节点的next与假节点是否相等,若是不等为该节点的next赋值成fakeNextip
Java实现:leetcode
public boolean hasCycle(ListNode head) { // check if head null if (head == null) return false; ListNode cur = head; ListNode fakeNext = new ListNode(0); // define a fake next while (cur.next != null) { if (cur.next == fakeNext) { return true; } else { ListNode tmp = cur; cur = cur.next; tmp.next = fakeNext; } } return false; }