Skip to main content

Nth Node from End in LinkedList

Nth Node from End in LinkedList
1) Find length of  linked list.
2) Traverse (length-position+1) element from begin.


 //nth Node from end
 public Node nodeFromEnd(Node head,int position){
  Node temp=head;
  int length=1;
  while(temp.next!=null)
  {
   length++;
   temp=temp.next;
  }
  System.out.println("length"+length);
  temp=head;
  int c=1;
  while(c!=(length-position+1))
  {
   temp=temp.next;
   c++;
  }
  return temp;
 }
 

Comments

.

Popular posts from this blog

BREADTH FIRST SEARCH IN JAVA

BREADTH FIRST SEARCH IN JAVA:- package com . problems . graph ; import java.awt.DisplayMode ; import java.util.Iterator ; import java.util.LinkedList ; public class BFSGraph { int maxsize ; Vertex vertexlist []; int matrixlist [][]; int vertexcount ; @SuppressWarnings ({ "rawtypes" , "unused" }) LinkedList queue ; public BFSGraph () { maxsize = 20 ; matrixlist = new int [ maxsize ][ maxsize ]; vertexlist = new Vertex [ maxsize ]; for ( int i = 0 ; i < maxsize ; i ++) { for ( int j = 0 ; j < maxsize ; j ++) { matrixlist [ i ][ j ]= 0 ; } } queue = new LinkedList (); } public void addVertex ( char label ) { vertexlist [ vertexcount ++]= new Vertex ( label ); } public void addEdge ( int i , int j ) { matrixlist [ i ][ j ]= 1 ; matrixlist [ j ][ i ]= 1 ; } public void displayVertex ( int v ) { System . out . println ( vertexlis

How to do Effective Programming?

There is no secret to doing effective programming but following a sequence of steps and procedures can help in building great programs. Today I will take you on a tour to some of the best practices that are integrants of perfect programs. Algorithms are important: - You can’t deny the fact that algorithms are important and before start to write any program, Algorithms are must to write. For example, if there is a program about finding the sum of two numbers? What will you write ?The steps can be :- 1)   Get the first number. 2)   Get the second number. 3)   Add both numbers. This is what algorithm is writing about ,a list of statements .From the above three statements you can conclude boundary cases (at least two number should be there in input), mathematical function(Sum is needed here) , storage capacity(amount of memory to be assign to the variables), number of methods by analyzing repeat steps (reduce replete codes) and many other things. During algorithm only yo