0

I am trying to write comments to understand a program to implement inserting a node at nth position

I am not able to understand the last line in insert function

temp2->next = temp1; //??temp 1 that points to new node will be assigned to new node pointer

So far pointer to nth node (as in previous for loop temp 2 will be pointing to nth node) will be assigned to pointer in the newly created node. So new node is now pointing to the previously nth node.

But I don't understand how in the next line previous n-1 node will point to new node

Also I find it hard to keep in mind if I am dealing with the pointer before the node or the pointer part of next node.

Any helpful tips and suggestions will be appreciated

#include "stdio.h" 
#include "stdlib.h"

struct Node

 {
 int data;

 struct Node* next;
 };

struct Node* head; //declares a pointer to first node called head

// define function to insert data  at poisition n

void Insert(int data, int n)

{
 struct Node* temp1 = malloc(sizeof( struct Node())); // Dynamic memory      allocation using pointer called temp1

(*temp1).data=data;
(*temp1).next = NULL;

 if (n == 1)   // if we enter in the 1st position

 {

  (*temp1).next = head; // temp1 is a pointer to malloced memory of a node whose pointer part will now take on same value as head 
                          // ie pointing to first node


   head = temp1;      // head pointer now becomes equal to temp1 pointer (that points to originally malloced node that thas become first node now)
   return;

 }

 struct Node* temp2 = head;

 for (int i = 0; i < n-2; i++)

  {
     temp2 = temp2->next;        // first step,temp 2 will take on the pointer value of first node, ie point to second node
                              //will take temp 2 pointer to pointing nth node


  }

 temp1->next = temp2->next;   // pointer to nth node (as in previous     loop temp 2 will be pointing to nth node) will be assigned to pointer in the newly created node

 temp2->next = temp1;        //??temp 1 that points to new node will be assigned to new node pointer

}
void Print()
{
 struct Node* temp = head;
 while (temp != NULL)
 {
  printf("%d", temp->data);
  temp = temp->next;

 }printf("\n");

}
 int main()
{
 head = NULL;
 printf("program begins..\n");
 Insert(2,1);
 Insert(5, 2);
 Insert(3, 3);

 Print();
}
0

Ok, I think I got this.

temp1->next = temp2->next;   

/* pointer to n+1 th node (and not n th node that I had in the question) will be assigned to pointer in the newly created node, hence pointer part of newly created node is pointing to n+1 th node */

temp2->next = temp1;       

/* temp 1 which points to new node will be assigned to the pointer part of nth node that therefore will make orignal nth node now point to new node which becomes nth node*/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .