Data World

Posts Tagged ‘linked list’

Python : Playing with Linked list

Posted by Pramod Singla on May 14, 2018


  • Create linked list and add node at the beginning

class node:

    def __init__(self, p_data):

        self.data=p_data

        self.next=None

class linkedlist:

    def __init__(self):

        self.head=None

        self.len=0

    def addNodeAtBegin(self,data):

        newNode=node(data)

        newNode.next=self.head

        self.head=newNode

        self.len=self.len+1

    def print(self):

        node=self.head

        while node:

            print(node.data)

            node=node.next

newlinkedList=linkedlist()

newlinkedList.addNodeAtBegin(10)

newlinkedList.print()

 

  • Linked list and add node in sorted list

class node:

    def __init__(self, p_data):

        self.data=p_data

        self.next=None

class linkedlist:

    def __init__(self):

        self.head=None

        self.len=0

    def addNodeAtBegin(self,data):

        newNode=node(data)

        newNode.next=self.head

        self.head=newNode

        self.len=self.len+1

    def sortedInsert(self,data):

        newNode=node(data)

        Curr=self.head

        if Curr==None or Curr.data>newNode.data:

            newNode.next=self.head

            self.head=newNode

        else:

            Next=Curr.next

            while Curr.data<=newNode.data:

                if Curr.next==None:

                    Curr.next=newNode

                    newNode.next=None

                    break;

                if Curr.data<=newNode.data and Next.data>=newNode.data:

                    Curr.next=newNode

                    newNode.next=Next

                    self.len=self.len+1

                    break

                Curr=Next

                Next=Next.next

    def print(self):

        node=self.head

        while node:

            print(node.data)

            node=node.next

newSortedlinkedList=linkedlist()

newSortedlinkedList.sortedInsert(10)

newSortedlinkedList.sortedInsert(20)

newSortedlinkedList.sortedInsert(30)

newSortedlinkedList.sortedInsert(15)

newSortedlinkedList.sortedInsert(10)

newSortedlinkedList.sortedInsert(30)

newSortedlinkedList.sortedInsert(40)

newSortedlinkedList.sortedInsert(5)

newSortedlinkedList.print()

 

Advertisements

Posted in Interview Questions, Python | Tagged: , | Leave a Comment »