33. Nth node from end of linked list

33. Nth node from end of linked list


Problem link :- click here


package Linked_List;

public class LinkedList__33
{
	/*
	 	Given a linked list consisting of L nodes and given a number N. The task is to 
	 	find the Nth node from the end of the linked list.
	 			1  2  3  4  5  6  7  8  9		N = 2
	 			output : 8
	 			
	 	If we know the size of the linked list, we can find the Nth node from the last.
	 	The formula is 		size - N
	 	i.e., we will maintain a variable to store the index, if the variable becomes 
	 	equal to that of the above formula then we are in the Nth node from the last.
	 	we will return that node.
	 */
	
	static int nthNodeFromLast(LinkedList list, int n)
	{
		int size = 0;
		Node temp = list.head;
		for(temp=list.head; temp!=null; temp=temp.next)
			size++;
		
		int count = 0;
		temp = list.head;
		for(temp=list.head; temp!=null; temp=temp.next)
		{
			if(count == size - n)
				return temp.data;
			count++;
		}
		return -1;
	}
	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.push(1);
		list.push(2);
		list.push(3);
		list.push(4);
		list.push(5);
		list.push(6);
		list.push(7);
		list.push(8);
		list.push(9);
		
		System.out.println("Linked list : ");
		printList(list);
		
		int n = 2;
		
		int ans = nthNodeFromLast(list, n);
		System.out.println("\nNth node from last is : " + ans);
	}

	static void printList(LinkedList list)
	{
		for(Node temp=list.head; temp!=null; temp=temp.next)
			System.out.print(temp.data + "-> ");
		System.out.println("null");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree