Nth node from end in a Linked List

 In this program we will see how to get nth node from the end in a Linked List.


linked list: 20=>40=>30=>80=>90=>
Input: 2
Output: 80


class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
class LinkedList:
    def __init__(self):
        self.head = None
    def display(self):
        temp = self.head
        while temp!=None:
            print(temp.data, end="=>")
            temp = temp.next
    def length(self):
        temp = self.head
        count=0
        while temp!=None:
            count = count+1
            temp = temp.next
        return count
    def NthNodeFromEnd(self,index):
        if index<0:
            print('Enter correct value')
        else:
            count = LinkedList.length(self)- index
            if count<0:
                print('Not a Valid index')
            else:
                #print('You have to print value', count)
                temp = self.head
                for i in range(count):
                    temp = temp.next
                print("Your data is ", temp.data)
if __name__=="__main__":
    #20=>40=>30=>80=>90=>
    llist = LinkedList()
    first = Node(20)
    second = Node(40)
    third = Node(30)
    fourth = Node(80)
    fifth = Node(90)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    llist.display()
    print("\nLength: ",llist.length())
    llist.NthNodeFromEnd(2)


Output:



            


No comments:

Post a Comment