題目大意:給一個鏈表,判斷是否存在循環,最好不要使用額外空間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; }