python - How to create add and remove function in a sorted doubly linked list -
here 3 classes: node, doubly linked list, , sorted list implement on doubly linked list. here code:
class dllnode(object): def __init__ (self, data, prev_node=none, next_node=none): self.data=data self.prev_node=prev_node self.next_node=next_node def __str__(self): return str(self.data) class doublylinkedlist(object): def __init__(self, head=none, tail=none): self.head=head self.tail=tail self.size=0 def add_to_head(self, data): newnode = dllnode(data) if self.head==none: self.head=self.tail=newnode self.head.prev_node=self.tail.next_node=none else: self.head.prev_node=newnode newnode.next_node=self.head self.head=newnode def add_to_tail(self, data): newnode=dllnode(data) if self.head==none: self.head=self.tail=newnode self.head.prev_node=self.tail.next_node=none else: self.tail.next_node=newnode newnode.prev_node=self.tail self.tail=newnode self.tail.next_node=none def remove_head(self): node=self.head if self.head==self.tail: self.prev_node=self.next_node=self.head=self.tail=none return if self.head!=self.tail: node=node.next_node node.prev_node=none self.head=node def remove_tail(self): node=self.tail if self.head==self.tail: self.prev_node=self.next_node=self.head=self.tail=none return if self.head!=self.tail: self.tail=node.prev_node self.tail.next_node=none def index(self,element): current = self.head while current != none: if current.data == element: return current.position else: current = current.next return -1 class sortedlist(object): def __init__(self, sequence = []): if len(sequence)==0: self.head = none self.tail = none else: cur_node = none prev_node = none sequence.sort() sequence.reverse() element in sequence: prev_node = cur_node cur_node = dllnode(element, cur_node, prev_node) self.head = cur_node self.tail = dllnode(sequence[0]) for sorted list class need create add , remove function. however, dont know how it. let me know?
Comments
Post a Comment