Skip to main content

Adding Node at a given position in Linked List

Adding Node at a given position in Linked List




public void addNodeAtPosition(Node head,int position,int data)
 {
  Node temp=head;
  //create a node
  Node node=new Node(data);
  int c=1;
  //while counter is not equal to the position
  while(c!=position)
  {
   temp=temp.next;
   c++;
  }
  //point node to the next of current node
  node.next=temp.next;
  //point next of current to the node to insert
  temp.next=node;
 }

To Know the basic structure of the linked list click here

Comments

.

Popular posts from this blog

5 steps to add existing project to your GIT HUB repository [Windows]

this tutorial will tell you how to add existing project to your git hub account. Step1. Go to your GITHUB account. Create New repository  add repository Step2. Fill the required details. ( uncheck create read me ). Add details   Step 3. Open GIT shell from your desktop. Step 4. Go to the directory of your project using cd  “path of the project” Initialize git by using command   git init Add your files by using command   git add . Commit your files by command git commit –m ‘first commit’ commands to add git   STEP 5 Select your repository Add using command git remote add origin https://github.com/username/projectname.git Now push the project to git git push -u origin master push command

Deleting a Node by passing data in LInkedList

Deleting a Node by passing data in LInkedList:- The node can be deleted by passing the data value in a function.Here we have three pointers one to traverse the list other to point current node and third one to point previous of current node. //deleting a given key public Node deleteKeyNode ( Node head , int key ) { //traverse pointer Node temp = head ; //previous pointer Node prevtemp = temp ; while ( temp != null ) { //when key is at head position if ( key == head . data ) { head = head . next ; System . out . println ( "head is deleted" ); return head ; } //when key is at any position other than head if ( temp . data == key ) { prevtemp . next = temp . next ; temp . next = null ; temp = prevtemp ; } prevtemp = temp ; temp = temp . next ; } return head ; }