Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Linked Lists Exercise - My Answer
- import time
- import os
- class Node:
- def __init__(self, contents=None, next=None):
- self.contents = contents
- self.next = next
- def get_contents(self):
- return self.contents
- def __str__(self):
- return str(self.contents)
- def print_list(node):
- while node:
- print(node.get_contents())
- node = node.next
- print()
- def add_to_list():
- print("Current linked list:")
- print_list(node1)
- try:
- print("If you wish to select a different option enter BACK")
- node_location = input("Enter the location you desire you data to be: ")
- if node_location == "BACK":
- print("Returning to menu...")
- time.sleep(1)
- os.system('cls')
- return main()
- node_location = int(node_location)
- except:
- print("This should be a number!")
- return add_to_list()
- temp = "node" + str(node_location)
- temp1 = "node" + str(node_location - 1)
- added_node = Node(input("Enter the desired data: "))
- try:
- globals()[temp1].next = added_node
- added_node.next = globals()[temp]
- except:
- pass
- print("The linked list now:")
- if (node_location - 1) == 0:
- added_node.next = node1
- print_list(added_node)
- else:
- print_list(node1)
- os.system('cls')
- return main()
- def delete_node():
- print("Current linked list:")
- print_list(node1)
- try:
- print("If you wish to select a different option enter BACK")
- location = input("Enter the location you want to delete: ")
- if location == "BACK":
- print("Returning to menu...")
- time.sleep(1)
- os.system('cls')
- return main()
- location = int(location)
- except:
- print("This should be a number!")
- return delete_node()
- temp = "node" + str(location)
- if globals()[temp] is None:
- print("This node does not exist")
- return delete_node()
- temp1 = "node" + str(location - 1)
- temp2 = "node" + str(location + 1)
- print("deleting:", globals()[temp].contents, "\n")
- globals()[temp1].next = globals()[temp2]
- os.system('cls')
- return main()
- def main():
- print("Current linked list:")
- print_list(node1)
- decision = input("Do you wish to add or delete: ")
- os.system('cls')
- if decision == "add":
- add_to_list()
- elif decision == "delete":
- delete_node()
- else:
- print("Invalid input")
- return main()
- node0 = None
- node1 = Node("Bob")
- node2 = Node("Car")
- node3 = Node("Sky")
- node4 = Node("Skidipap")
- node1.next = node2
- node2.next = node3
- node3.next = node4
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement