master-algorithms-py/linked_lists
2023-08-02 18:34:17 -07:00
..
detect_cycle.py Update detect_cycle.py 2023-08-02 16:40:19 -07:00
detect_cycle_II.py Create detect_cycle_II.py 2023-08-02 17:06:05 -07:00
doubly_linked_list.py Update and rename double_linked_list.py to doubly_linked_list.py 2023-08-02 18:24:28 -07:00
doubly_linked_list_II.py Create doubly_linked_list_II.py 2023-08-02 18:34:17 -07:00
finding_intersection.py Create finding_intersection.py 2023-08-02 17:14:46 -07:00
linked_list_fifo.py Rename LinkedListFIFO.py to linked_list_fifo.py 2023-07-31 11:59:00 -07:00
linked_list_II.py Update linked_list_II.py 2023-08-02 16:41:10 -07:00
merge_two_lists.py Create merge_two_lists.py 2023-07-31 13:44:12 -07:00
README.md add notes on reversing 2023-08-02 18:17:34 -07:00
remove_kth_node.py Create remove_kth_node.py 2023-08-02 17:46:34 -07:00
reverse_linked_list.py Update reverse_linked_list.py 2023-08-02 17:49:22 -07:00
reverse_linked_list_II.py Create reverse_linked_list_II.py 2023-08-02 18:13:43 -07:00
swap_every_two_nodes.py Create swap_every_two_nodes.py 2023-07-31 12:00:18 -07:00

Linked List


  • each node in a singly-linked list contains a valye and a reference fiedl to link to the next node. the head node (first node) usually represents the whole list.

  • unlike an array, a linked list does not provide constant time access to an index (as it needs to interact through all k elements), however addition and removal of elements are constant time.

  • nodes can be added at the beginning, head needs to be update (current -> head and head = current).

  • to remove a node you set prev.next equal to node.next. if it's a double list, you also update node.next with node.next.prev to node.prev (and deallocate the memory).



detecting cycles


  • can be done with hash table or the two-pointer technique, where if there is no cycle, the faster pointer (going 2 steps) will stop at the end of the list, but if there is a cycle, the fast pointer will eventually meet the slow pointer (going 1 step).

  • if there is no cycle, the faster pointer takes N/2 to reach the end of the list (N being the length).



reversing the list


  • keep track of the original head node and the new head node (for instance, with two pointers).

def reverse_list(head):

  if head is None:
      return head
        
  final_head = head
        
  while head.next:
      
      new_node = head.next
      head.next = new_node.next
      new_node.next = final_head
      final_head = new_node
        
  return final_head



some exercises in this dir


LinkedListFIFO.py


python LinkedListFIFO.py

Linked List FIFO
Add 1: None
Add 2: Nonew
Add 3: None
Length: 3
Find 1: (None, None, 0)
Delete 1: None
Length: 0
Find 1: (None, None, 0)