To print the middle term of a linked list

 In this program we will print the middle term of a linked list

If there is odd number of nodes then middle term will be only one number


Input: 10=>20=>30=>40=>50=>
Output: 30

But if there is even number of nodes then there will be two middle term so in such case we will print the second middle term


Input: 10=>20=>30=>10=>40=>50=>
Output: 10


Program:

class Node:
    def __init__(self,data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def length(self):
        temp = self.head
        count = 0
        while temp!=None:
            count = count+1
            temp=temp.next
        return count
    def middle(self):
        length1 = self.length()
        
        if length1%2==0:
            flag = (length1/2)+1
            return self.nthNode(flag)
        else:
            flag = (length1+1)/2
            return self.nthNode(flag)

    def nthNode(self,index):
        temp=self.head
        count = 1
        while temp!=None:
            if count==index:
                
                return temp.data
                
            else:
                temp=temp.next
                count = count+1
                
        
if __name__=="__main__":
    llist = LinkedList()
    first = Node(10)
    second = Node(20)
    third = Node(30)
    fourth = Node(10)
    fifth = Node(50)
    sixth = Node(60)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    fifth.next = sixth
    print(llist.middle())

No comments:

Post a Comment