Skip to main content

Delete node at a given position in Linked List

Delete node at a given position in Linked List



//delete node by position in linked list
 public Node deleteKeyAtPosition(Node head,int position)
 {
  
  Node temp=head;
  Node prevtemp=temp;
  int c=1;
  //if position is head
  if(position==1)
  {
   head=head.next;
   return head;
  }
  //position +1 because we have to go till that point
  while(c!=position+1)
  {
   if(c==position && position!=1)
   {
    prevtemp.next=temp.next;
    temp.next=null;
    temp=prevtemp;
   }
   prevtemp=temp;
   temp=temp.next;
   c++;
  }
  return head; 
 }

Comments

.

Popular posts from this blog

Adding Node at the End of Linked List

Adding Node at the End of Linked List:- The method takes two parameter one a head node of a linked list and other data too insert. public void addNodeEnd ( Node head , int data ) { if ( head == null ) { System . out . println ( "list is empty" ); return ; } Node node = new Node ( data ); Node temp = head ; while ( temp . next != null ) { temp = temp . next ; } temp . next = node ; } To Know the basic structure of the linked list click here

DEPTH FIRST SEARCH IN JAVA

DEPTH FIRST SEARCH IN JAVA public void dfs () { vertex [ 0 ]. visited = true ; displyVertex ( 0 ); stackobj . push ( 0 ); while (! stackobj . isEmpty ()) { int v = adjVertex (( Integer ) stackobj . peek ()); if ( v ==- 1 ) { stackobj . pop (); } else { vertex [ v ]. visited = true ; displyVertex ( v ); stackobj . push ( v ); } } }