Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. '''
  2. 19. Remove Nth Node From End of List
  3.  
  4. Hi, here's your problem today. This problem was recently asked by AirBNB:
  5.  
  6. You are given a singly linked list and an integer k.
  7. Return the linked list, removing the k-th last element from the list.
  8.  
  9. Try to do it in a single pass and using constant space.
  10. '''
  11. class Node:
  12. def __init__(self, val, next=None):
  13. self.val = val
  14. self.next = next
  15. def __str__(self):
  16. current_node = self
  17. result = []
  18. while current_node:
  19. result.append(current_node.val)
  20. current_node = current_node.next
  21. return str(result)
  22.  
  23. class Solution:
  24. def removeNthFromEnd(self, head: Node, n: int) -> Node:
  25. root = Node(-1, head)
  26. first, second = root, root
  27. for i in range(n+1):
  28. first = first.next
  29. while first is not None:
  30. first = first.next
  31. second = second.next
  32. second.next = second.next.next
  33. return root.next
  34.  
  35. head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
  36. print(head)
  37. # [1, 2, 3, 4, 5]
  38. head = Solution().removeNthFromEnd(head, 3)
  39. print(head)
  40. # [1, 2, 4, 5]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement