Doubly Final
shinta0x01
python
2 years ago
3.9 kB
6
Indexable
class Node: def __init__(self, data): self.prev = None self.data = data self.next = None class Doubly: def __init__(self): self.head = None def insert_begin(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node def insert_end(self, data): new_node = Node(data) current = self.head if self.head is None: self.head = new_node else: while current.next != None: current = current.next current.next = new_node new_node.prev = current def insert_before(self, key, data): new_node = Node(data) current = self.head if self.head is None: print('List is empty') return if current.data == key: new_node.next = self.head self.head.prev = new_node return while current.data != key: current = current.next current.prev.next = new_node new_node.next = current current.prev = new_node def insert_after(self, key, data): new_node = Node(data) current = self.head if current.data == key: post_current = current.next current.next = new_node new_node.prev = current new_node.next = post_current post_current.prev = new_node return if self.head is None: print('Empty') return while current.data != key: current = current.next post_current = current.next if current.data != key and current.next is None: print('Empty') return if post_current.next is None and post_current.data == key: post_current.next = new_node new_node.prev = post_current return current.next = new_node new_node.prev = current new_node.next = post_current post_current.prev = new_node def del_first(self): current = self.head if self.head is None: print('Empty') else: self.head = current.next self.head.prev = None def del_last(self): current = self.head if self.head is None: print('empty') else: while current.next != None: pre_current = current current = current.next pre_current.next = None def del_given(self, key): current = self.head if self.head is None: print('empty') return if current.data == key: current = current.next current.prev = None self.head = current return while current.data != key: current = current.next current.prev.next = current.next def display(self): current = self.head while current != None: print(current.data, '', end='') current = current.next def concatenated(self, d1): current = self.head while current.next != None: current = current.next current.next = d1.head d = Doubly() d1 = Doubly() #5 8 9 10 d.insert_begin(10) d.insert_begin(9) d.insert_begin(8) d.insert_begin(5) d.insert_end(11) d.insert_end(20) d.insert_before(8, 90) d.insert_after(20, 100) d.del_last() # d.del_given(20) print('xa') d.display() print() d1.insert_begin(1) d1.insert_begin(2) d1.insert_begin(5) d1.insert_begin(8) d.display() print() d1.display() d.concatenated(d1) d.display()
Editor is loading...
Leave a Comment