class Node: def __init__(self, val = None): self.val = val self.next = None class LinkedList: def __init__(self): self.head = Node() def addLast(self, val): newNode = Node(val) cur = self.head while cur.next != None: cur = cur.next cur.next = newNode def addBeg(self, val): new = Node(val) cur = self.head last = cur cur = cur.next last.next = new new.next = cur def addPos(self, val, pos): new = Node(val) cur = self.head count = 0 while True: last = cur cur = cur.next if pos == count: last.next = new new.next = cur return count += 1 def removeVal(self, val): cur = self.head while True: last = cur cur = cur.next if cur.val == val: last.next = cur.next return def removeIndex(self, index): cur = self.head count = 1 while True: last = cur cur = cur.next if count == index: last.next = cur.next return count += 1 def printList(self): l = [] temp = self.head while temp.next != None: temp = temp.next l.append(temp.val) print(l) linked = LinkedList() linked.addLast(1) linked.addLast(2) linked.addLast(3) linked.addLast(5) linked.printList() linked.addBeg(0) linked.printList() linked.addPos(4, 1) linked.printList() linked.removeVal(4) linked.printList() linked.removeIndex(3) linked.printList()
0 Comments
Please don't enter any spam link in comment box.
Emoji