LL141LinkedListCycle

来源:互联网 发布:java 生成汉字五笔码 编辑:程序博客网 时间:2024/06/01 08:39

思路

  1. use two pointers, one is fast, one is slow.
    • When the two meet, it has cycle
    • Bug:
      • Have to make sure the pointer is not null, and its next is not null before assigning the pointer, e.g. fast = fast.null
      • hasCycleTwoPointers2() optimize the while condition.

Remember

  • if ListNode ln = new ListNode(3), then ln.next == null. The next pointer is always exists. So we don’t need to check ln.next != null if we assign fast = ln.next;
while(fast != null && fast.next != null) {     fast = fast.next.next;     if (fast == slow) return true;     slow = slow.next; }
  • Remove element while iterating the set is not elegant. http://stackoverflow.com/questions/1110404/remove-elements-from-a-hashset-while-iterating
0 0
原创粉丝点击