Advertisement
Guest User

Untitled

a guest
Jun 19th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. class Node:
  2. def __init__(self, data, next = None):
  3. self.data = data
  4. self.next = next
  5.  
  6. def __getitem__(self, index):
  7. head = self
  8. while index > 0:
  9. if head.next is not None:
  10. head = head.next
  11. index -= 1
  12. else:
  13. raise IndexError
  14. return head.data
  15.  
  16. def set(self, new_item, index):
  17. head = self
  18. while index > 0:
  19. if head.next != None:
  20. head = head.next
  21. index -= 1
  22. else:
  23. raise IndexError
  24. head.data = new_item
  25. return head.data
  26.  
  27. def insert(self, new_item, index):
  28. head = self
  29. while index > 0:
  30. if head.next != None:
  31. head = head.next
  32. index -= 1
  33. else:
  34. return None
  35. head.next = Node(new_item, head.next)
  36.  
  37.  
  38. if __name__ == '__main__':
  39. n = Node(2, Node(8, Node(10)))
  40. n.insert(7, 2)
  41. while n != None:
  42. print(n.data)
  43. n = n.next
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement