Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://leetcode.com/problems/remove-linked-list-elements/
- # out-of-place
- new_list = None
- result = None
- while head is not None:
- if head.val != val:
- # 1st case: new_list is None
- # have to initialize the new_list
- if new_list is None:
- new_list = ListNode(head.val)
- result = new_list
- # 2nd case: new_list is not None
- # new_list is already a node of something
- # initialize new_list.next
- # go to new_list.next
- else:
- new_list.next = ListNode(head.val)
- new_list = new_list.next
- head = head.next
- return result
- # with stack
- curr = head
- stack = []
- while curr is not None:
- if curr.val != val:
- stack.append(curr)
- curr = curr.next
- stack.append(None)
- curr_elem = stack[-1] # get the top in stack
- stack.pop() # remove the top element from stack
- while len(stack) > 0:
- # chain the current top element with curr_elem
- top_elem = stack[-1]
- stack.pop()
- top_elem.next = curr_elem
- curr_elem = top_elem
- return curr_elem
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement