quachtridat

[LeetCode] Remove Linked List Elements

May 9th, 2021
941
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # https://leetcode.com/problems/remove-linked-list-elements/
  2.  
  3. # out-of-place
  4. new_list = None
  5. result = None
  6.  
  7. while head is not None:
  8.     if head.val != val:
  9.         # 1st case: new_list is None
  10.         # have to initialize the new_list
  11.         if new_list is None:
  12.             new_list = ListNode(head.val)
  13.             result = new_list
  14.         # 2nd case: new_list is not None
  15.         # new_list is already a node of something
  16.         # initialize new_list.next
  17.         # go to new_list.next
  18.         else:
  19.             new_list.next = ListNode(head.val)
  20.             new_list = new_list.next
  21.     head = head.next
  22. return result
  23.  
  24. # with stack
  25. curr = head
  26.  
  27. stack = []
  28. while curr is not None:
  29.     if curr.val != val:
  30.         stack.append(curr)
  31.     curr = curr.next
  32.  
  33. stack.append(None)
  34.  
  35. curr_elem = stack[-1] # get the top in stack
  36. stack.pop() # remove the top element from stack
  37.  
  38. while len(stack) > 0:
  39.     # chain the current top element with curr_elem
  40.     top_elem = stack[-1]
  41.     stack.pop()
  42.     top_elem.next = curr_elem
  43.     curr_elem = top_elem
  44.  
  45. return curr_elem
  46.            
RAW Paste Data