Data structures in Python, Series 1.2: Linked Lists

Removing a node from the list at

(i) begining
(ii)inbetween nodes
(iii)at the end

So the removenode() in the class linkedlist does the above operation.

give data-structures-in-python-series-1.1 a read before attempting the below code. 

# Firt of all make a node class for every future node to be shaped like .
# Firt of all make a node class for every future node to be shaped like . class node(): def __init__(self,data,nextnode = None): self.data = data self.nextnode = nextnode #now make a class with the all the operations that can be operated in a list #remember do get a __init__ as this will be used to initiate the default values for the instance in main class linkedlist(): def __init__(self): self.head = None self.data = 0 self.size = 0 def addnode(self,data): self.data = data new = node(data,self.head) self.head = new self.size +=1 def __print__(self): cur = self.head while cur: print(str(cur.data),end = '>>') cur = cur.nextnode print('None') def removenode(self,data): cur = self.head prev = None while cur: if cur.data == data: if prev: prev.nextnode = cur.nextnode cur.nextnode = None else: prev = cur cur = cur.nextnode prev.nextnode = None self.head = cur return True prev = cur cur = cur.nextnode return False
    def deletenodeposition(self,position):
        cur = self.head
        prev = None
        Next = None
        #first of all lets go to the position before the required position
        if self.head == None:
            return True
        
        if position == 0:
            prev = cur
            cur = cur.nextnode
            prev.nextnode = None
            return True
        for i in range(position-1):
            cur = cur.nextnode
            if cur ==  None:
                break
        if cur == None:
            return True
        if cur.nextnode == None:
            return True
        prev = cur.nextnode
        cur.nextnode = cur.nextnode.nextnode
        prev.nextnode = None
        return True

if __name__ == '__main__': lis = linkedlist() for i in range(int(input('enter the number of elements to be inserted'))): lis.addnode(int(input('enter the value'))) lis.__print__()

Comments

Popular Posts