I tried to insert a node before a given node by specifying the position of the node before which I want to insert the newnode. I got the data present inside that node's position and using a while loop, compared this data with each node's data till I reached the point where I was supposed to insert the node.
But when I tried displaying the elements using a while statement my program went into an infinte loop.I checked where the head node was pointing to and its to pointing to the first node of the singly list only. Could someone please help me out?
#include <iostream>
#include<stdlib.h>
using namespace std;
void display(struct node *);
struct node{
int data;
struct node *next;
};
struct node *ptr,*head=NULL;
void insertt(struct node *head){ //insert function to insert node before a node
struct node *ptr1=head;
int pos,poss,value;
cin>>poss; //getting position and value
cin>>value;
pos=poss-1;
while(pos--){ //moving to that position
ptr1=ptr1->next;
}
struct node *ptr2=ptr1;
struct node *newnode = (struct node*)malloc(sizeof(struct node)); //creating new node for insertion
newnode->next=NULL;
newnode->data=value;
struct node *preptr;
preptr=ptr1;
int c=ptr2->data; //getting value present in that particular position(node) of the list
while(ptr1->data!=c){ //inserting before node
preptr=ptr1;
ptr1=ptr1->next;
}
preptr->next=newnode;
newnode->next=ptr1;
display(head);
}
void display(struct node *head){ //displaying linked list
struct node *ptr2=head;
while(ptr2!=NULL){
cout<<ptr2->data;
ptr2=ptr2->next;
}
}
int main()
{
int n,val,i;
cin>>n; //number of nodes
for(i=0;i<n;i++){ //node creation
cin>>val;
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(head==NULL){
ptr=head;
head=newnode;
}
else{
ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=newnode;
}
}
insertt(head); //insertion
return 0;
}
ptr1
, you set preptr
and ptr2
to ptr1
.c = ptr2->data
, which happens to be the same as ptr1->data
.while (ptr1->data != c)
, which is always false. So that bottom while
loop does nothingpreptr
and ptr1
pointing to the same node n
.n->next
(preptr->next
) point to newnode
, and newnode->next
point to ptr1
(n
): an infinite loop. n newnode
-------- ---------
preptr ---> | c | | value |
ptr1 ---> -------- ---------
| next | ---> | |
| | <--- | next |
-------- ---------
void insertt(struct node *head) {
struct node *ptr1 = head;
int pos, poss, value;
cin >> poss;
cin >> value;
pos = poss - 1;
while (pos--) {
ptr1 = ptr1->next;
}
struct node *ptr2 = ptr1;
struct node *newnode = (struct node *) malloc(sizeof(struct node));
newnode->next = NULL;
newnode->data = value;
struct node *preptr;
preptr = ptr1; // ptr1, ptr2, and preptr point to the same node n
int c = ptr2->data; // c = ptr1->data too
while (ptr1->data != c) { // always false
preptr = ptr1;
ptr1 = ptr1->next;
}
preptr->next = newnode; // n->next = newnode
newnode->next = ptr1; // newnode-next = n
display(head);
}