I want to add a node at ith position.
I added a head node and a node at position 4, 5 and 3 in sequence with value of
1,2,3,4 respectively.
I also have a print function to print the values of the nodes.
But my print function only prints the value of the head node (1) but not the values of rest of the nodes.
my desired output as follows
it will be something like this
add head node, data = 1
add node at position 4 = 2
add node at position 5 = 3
add node at position 3 = 4
and the output will be
1>4>2>3 = values of head node, node at 3 position, node at 4 position and node at 5 position
and if I add node at position 2 = 6
the output will become
1>6>4>2>3
this is what I have tried
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
typedef struct node {
int data;
node *next;
}nodeType;
node *headNode()
{
nodeType * head = NULL;
nodeType * temp = new nodeType;
temp->data= 1;
if(head == NULL)
{
head = temp;
}
return head;
}
node *addNode(int pos, int value, node *head)
{
nodeType *n = new nodeType;
n->data = value;
n->next = NULL;
if(head != NULL)
{
int dist = 1;
node *trans = head;
while(trans != NULL)
{
if(dist == pos)
{
n->next = trans->next;
trans->next= n;
return head;
}
trans = trans->next;
dist++;
}
}
return n;
}
void printall(node *head){
nodeType *temp =head;
if(temp==NULL){
std::cout << "\n\n\tError";
} // if
else{
while(temp!=NULL){
std::cout << temp->data << " ";
temp=temp->next;
}
}
}
int main()
{
node * head = headNode();
addNode(4, 2, head);
addNode(5, 3, head);
addNode(3, 4, head);
printall(head);
}