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

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

Shortest Path from source to Vertex :- Dijkstra Algorithm

Shortest Path from source to Vertex :- Dijkstra Algorithm:- Dijkstra  Algorithms is an algorithm use to find the shortest path from source vertex to a given vertex. package Graph ; import java.util.HashMap ; abstract public class DirectedGraph { Vertex [] vertexlist = new Vertex [ 10 ]; HashMap < Character , HashMap < Character , Integer >> edgelist = new HashMap <>(); Vertex vertex ; //count of vertex and edge static int vertexcount = 0 ; int edgecount = 0 ; /* * This function takes a label and insert in the vertex list as well as edge list since it is new vertex it will add * null to its adjoining vertices */ int addVertex ( char label ) { vertex = new Vertex ( label ); vertexlist [ vertexcount ]= vertex ; System . out . println ( vertexlist [ vertexcount ]. label ); edgelist . put ( vertex . label , null ); vertexcount ++; return vertexcount ; } int addEdge ( char label , char []