class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def insertAfter(self, prev, new_data): if prev is None: print("The given previous node must in LinkedList") return new_node = Node(new_data) new_node.next = prev.next prev.next = new_node def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.go_to_end(self.head) last.next = new_node def delete(self, key, node=None): temp = self.head if temp is not None: if temp.data == key: self.head = temp.next temp = None return prev, temp = self.search_recursion(key, temp) if temp is None: return prev.next = temp.next temp = None def go_to_end(self, head): if head.next: head = head.next self.go_to_end(head) return head.next def search_recursion(self, key, node=None): if node is not None: if node.data != key: node = node.next self.search_recursion(key, node) return node, node.next def printLinkList(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next if __name__ == '__main__': list = LinkedList() list.push(4) list.push(5) list.push(6) list.push(7) list.printLinkList() list.delete(5) list.printLinkList()
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter