Advertisement
AquaBlitz11

Linked List (recursive, no tails)

Jul 15th, 2020
945
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, val, nxt=None):
  3.         self.val = val
  4.         self.nxt = nxt
  5.  
  6. def insert_front(head, val):
  7.     return Node(val, head)
  8.  
  9. def insert_back(head, val):
  10.     if head == None:
  11.         return Node(val)
  12.     head.nxt = insert_back(head.nxt, val)
  13.     return head
  14.  
  15. def delete_front(head):
  16.     if head == None:
  17.         raise IndexError("deleting from an empty list")
  18.     return head.nxt
  19.  
  20. def delete_back(head):
  21.     if head == None:
  22.         raise IndexError("deleting from an empty list")
  23.     if head.nxt == None:
  24.         return None
  25.     head.nxt = delete_back(head.nxt)
  26.     return head
  27.  
  28. def delete_one(head, val):
  29.     if head == None:
  30.         # no val found, so no deletion
  31.         return None
  32.     if head.val == val:
  33.         return head.nxt
  34.     head.nxt = delete_one(head.nxt, val)
  35.     return head
  36.  
  37. def delete_all(head, val):
  38.     if head == None:
  39.         # no val found, so no deletion
  40.         return None
  41.     if head.val == val:
  42.         return delete_all(head.nxt, val)
  43.     head.nxt = delete_all(head.nxt, val)
  44.     return head
  45.  
  46. def reverse_list(head):
  47.     if head == None or head.nxt == None:
  48.         return head
  49.     # split list into 1 -> [2 -> 3 -> 4 -> None]. 2 is "nbeforetail"
  50.     nbeforetail = head.nxt
  51.     nhead = reverse_list(head.nxt)
  52.     # once reversed nlist, we have [4 -> 3 -> 2 -> None]
  53.     # so we link from nbeforetail to our old head and get 4 -> 3 -> 2 -> 1 -> None
  54.     nbeforetail.nxt = head
  55.     head.nxt = None
  56.     return nhead
  57.  
  58. def print_list(head):
  59.     if head == None:
  60.         print("")
  61.         return
  62.     print(head.val, end=" ")
  63.     print_list(head.nxt)
  64.  
  65. li = None
  66. li = insert_front(li, 5)
  67. li = insert_front(li, 20)
  68. li = insert_front(li, 10)
  69. li = insert_front(li, 15)
  70. li = insert_front(li, 20)
  71. li = insert_back(li, 2)
  72. li = insert_back(li, 4)
  73. li = insert_front(li, 15)
  74. li = insert_back(li, 4)
  75. print_list(li)
  76. li = reverse_list(li)
  77. print_list(li)
  78. li = delete_all(li, 20)
  79. li = delete_one(li, 15)
  80. li = delete_all(li, 4)
  81. print_list(li)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement