l2 linkedlist ListLinked Corner Case in Linked List

pre-sum and tow-pointer

tow pointers: suitable for arrays with positive numbers
pre-sum: ① array / HashMap; ② suitable for arrays with both positive and negative numbers; ③ cautions to overflow, especially with multiplication

ListLinked

Singly Linked List

Delete

1
2
public static ListNode delete(ListNode head, int value)
node.next = node.next.next;

Because the head may be deleted, so return a listnode instead of void.
PS: revise the Nth node, operate with the (N-1)th node

Exercise

[Trick] Dummy Node

1
2
3
4
ListNode dummy = new ListNode(0);
dummy.next = head;
...
return dummy.next;

LC 19 remove nth node from end

[go through one time] find the (n+1)th node from end
[Method] two pointers

  • P1 go n steps
  • P2 go from dummy

LC 142 entry point in list loop

  • if there is a loop in the list
    two points, one go fast (2 steps a time), one go slow; if they meet
  • locate the entry when n nodes in the loop
    if there are n nodes, P1 go n steps in advance, P2 then follow, they meet at the entry
  • how to count
    find any loop node and move along until go back

LC 160 Intersection of two linked lists

[method1] find the length of L1 and L2
P1 go advance (L1-L2) steps
[method2] make a loop by connecting L1’s head with common’s tail node

LC 206 reverse a list in O(1)

[method1] Stack [O(n)space]
[method2] recursion
[method3] know the ith next previous node

LC 445 Add numbers in lists **

reverse L1 and L2 and add in digits and remember the carry-bit
PS: the result’s length might be longer than the origial

  • reverse L1, L2
  • reverse add(L1,L2)

Doubly Linked List

{
ListNode next;
ListNode prev;
}

Exercise

Convert BST to Doubly Linked List

[Rotation] waiting to study

Circular Linked List

[facebook] Keep circular linked list sorted

waiting to study
new node: max, min, in between
using prev, next

  • in between: prev < n < next
  • min: after maxList
  • max: after maxList
    special case: only 1 node; null list

Corner Case in Linked List

  • empty lists
  • lists with only node
  • head node
  • tail node