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

Tree Traversal in JAVA (InOder/preOrder/postOrder)

Tree Traversal in JAVA (InOder/preOrder/postOrder):-

Tree traversal can be done through three ways.

1)Inorder:-

Go recursively to the left node.
Read a node
Go recursively to the right node.

2)Pre Order.

Read a node
Go recursively to the left node.
Go recursively to the right node.


2)Post Order.


Go recursively to the left node.
Go recursively to the right node.
Read a node



publicvoidinorder(Node root){if(root==null){return;} inorder(root.left); System.out.print(root.data+","); inorder(root.right);}publicvoidpreOrder(Node root){if(root==null){return;} System.out.print(root.data+","); preOrder(root.left); preOrder(root.right);}publicvoidpostOrder(Node root){if(root==null){return;} postOrder(root.left); postOrder(root.right); System.out.print(root.data+",");}