linked list and operations

rajeevsinghthakur · updated September 16, 2021 · Python
class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class linkedlist:
    def __init__(self):
        self.head = None
    def push(self,data):
        data = Node(data)
        data.next=self.head
        self.head=data
    def reversed(self):
        prev = None
        current = self.head
        while(current):
            next = current.next
            current.next = prev
            prev = current
            current = next
        self.head = prev
    def append(self,data):
        data = Node(data)
        if self.head == None:
            self.head = data
            return
        last = self.head
        while(last.next):
            last= last.next
        last.next =data
    def countlist(self):
        count = 0
        n = self.head
        while(n):
            count +=1
            n = n.next
        return count
    def search(self,x):
        current = self.head
        while(current != None):
            if current.data == x:
                return True 
            current = current.next
     
            
        return False
    def printlist(self):
        if self.head == None:
            print("list is empty",end="")
            return
        n = self.head
        while(n):
            print("---->",n.data,end="")
            n =n.next
    def getnthpos(self,index):
        count = 0
        current = self.head
        while(current):
            if count == index:
                 return current.data
            count += 1
            current =current.next
        #assert(False)
        return 0
           
l=linkedlist()

l.push(4)
l.push(65)
l.push(464)
print("length of list",end="")
print(" ")
print(l.countlist())
print("list is--->")
l.printlist()
print("")
print("reversed list")
l.reversed()

l.printlist()
print(" ")
print("append list")
l.append(56)

l.printlist()
print(" ")
print(l.search(464))

print(l.getnthpos(1))



            
        
            

Comments

rajeevsinghthakur September 16, 2021

Linked list implementation and relative operations

Please sign up or log in to contribute to the discussion.