data structures - Sorted Linked List in Python -
i'm having bit of trouble figuring out how sort singly linked list in python. i've figured out how create linked list , push data onto how push in sorted format (not sorting after data pushed onto it) or sorting in way?
objective
create sorted singly linked list of numbers based upon user input. program logic: ask number, add number list in sorted position, print list. repeat until enter -1 number.
current code
#!/usr/bin/env python class node: def __init__(self): self.data = none # contains data self.next = none # contains reference next node class linked_list: def __init__(self): self.cur_node = none def add_node(self, data): new_node = node() # create new node new_node.data = data new_node.next = self.cur_node # link new node 'previous' node. self.cur_node = new_node # set current node new one. def list_print(self): node = self.cur_node # cant point ll! while node: print(node.data) node = node.next def main(): ll = linked_list() num=int(input("enter num push onto list, -1 stop: ")) while num!=-1: data=num ll.add_node(data) num=int(input("enter num push onto list, -1 stop: ")) print("\n") ll.list_print() main()
i'm stuck here. thank in advance help!
this should it:
>>> class node: ... def __init__(self): ... self.data = none ... self.next = none ... >>> class linkedlist: ... def __init__(self): ... self.head = none ... ... def addnode(self, data): ... curr = self.head ... if curr none: ... n = node() ... n.data = data ... self.head = n ... return ... ... if curr.data > data: ... n = node() ... n.data = data ... n.next = curr ... self.head = n ... return ... ... while curr.next not none: ... if curr.next.data > data: ... break ... curr = curr.next ... n = node() ... n.data = data ... n.next = curr.next ... curr.next = n ... return ... ... def __str__(self): ... data = [] ... curr = self.head ... while curr not none: ... data.append(curr.data) ... curr = curr.next ... return "[%s]" %(', '.join(str(i) in data)) ... ... def __repr__(self): ... return self.__str__() ... >>> def main(): ... ll = linkedlist() ... num = int(input("enter number: ")) ... while num != -1: ... ll.addnode(num) ... num = int(input("enter number: ")) ... c = ll.head ... while c not none: ... print(c.data) ... c = c.next ... >>> main() enter number: 5 enter number: 3 enter number: 2 enter number: 4 enter number: 1 enter number: -1 1 2 3 4 5
Comments
Post a Comment