Untitled
unknown
python
2 months ago
2.9 kB
5
Indexable
# Double Linked List class Node: def __init__(self,data =None,plink =None,nlink =None): self.data = data self.plink = plink self.nlink = nlink class DoubleLinkedList: def __init__(self): self.head = None def insert_end(self,ndata): iNode = Node(ndata) if self.head == None: self.head = iNode return curNode = self.head while curNode.nlink is not None: curNode = curNode.nlink curNode.nlink = iNode iNode.plink = curNode def insert_begin(self,ndata): iNode = Node(ndata) if self.head is None: self.head = iNode return iNode.nlink = self.head self.head.plink = iNode self.head = iNode def inser_in_nth(self,ndata,n): if n == 0: self.insert_begin(ndata) return iNode = Node(ndata) curNode = self.head c = 0 while curNode is not None and c < n-1: curNode = curNode.nlink c += 1 if curNode is None: return iNode.nlink = curNode.nlink # Link new node to the next node if curNode.nlink is not None: # If not inserting at the end curNode.nlink.plink = iNode # Update the previous link of the next node curNode.nlink = iNode # Link current node to the new node iNode.plink = curNode # Link new node back to the current node # CurNode ndata curNode.nlink def delete_head(self): if self.head is None: print("No List") return if self.head.nlink is None: self.head = None return self.head = self.head.nlink self.head.plink = None def delete_end(self): if self.head is None: print("No List") return if self.head.nlink is None: self.head = None return curNode = self.head while curNode.nlink is not None: curNode = curNode.nlink curNode.plink.nlink = None curNode.plink = None #Breaks backward link def display(self): if self.head is None: print("List is empty") return curNode = self.head while curNode is not None: print(curNode.data, end=" -> ") curNode = curNode.nlink print("None") # End of list def display_reverse(self, curNode): if curNode is None: print("None", end=" <- ") # Print None at the start return self.display_reverse(curNode.nlink) # Recursive call to the next node print(curNode.data, end=" <- ")
Editor is loading...
Leave a Comment