Home > Blockchain >  How to avoid getting garbage values while inserting a new node after a given node in singly linked l
How to avoid getting garbage values while inserting a new node after a given node in singly linked l

Time:10-30

I was restricted to using only one way of inserting a new node after a given node and implementing the linked list. I was getting a garbage value in my output. I'm not clear on how I can resolve this issue. Any help is appreciated thanks in advance.


#include<stdio.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node *next;
};

void insertAfter(struct Node  *prevNode,int newData){
    if(prevNode == NULL){
        printf("the given previous node cannot be NULL");
        return;
    }
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->next = prevNode->next;
    prevNode->next = newNode;
}
void printList(struct Node *head){
    while(head!=NULL){
        printf(" %d ", head->data);
        head = head->next;
    }
}


int main()
{

  struct Node* head = NULL;
  struct Node* second = NULL;
  struct Node* third = NULL;
  
  head = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));

  head->data = 9;
  head->next = second;
  insertAfter(head->next, 8);
  third->data = 10;
  third->next = NULL;

  printf("\n Created Linked list is: ");
  printList(head);
 
  return 0;
}

Generated output:: 9 0 8 Expected output: 9 8 10

CodePudding user response:

This code snippet

  struct Node* head = NULL;
  struct Node* second = NULL;
  struct Node* third = NULL;
  
  head = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));

  head->data = 9;
  head->next = second;
  insertAfter(head->next, 8);
  third->data = 10;
  third->next = NULL;

is wrong. The node pointed to by the pointer third is not included in the list and the node pointed to by the pointer second has uninitialized data members.

At least you should write for example

  struct Node* head = NULL;
  struct Node* second = NULL;
  struct Node* third = NULL;
  
  head = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));

  head->data = 9;
  head->next = second;
  second->data = 10;
  second->next = third;  
  third->data = 11;
  third->next = NULL;
  insertAfter(head->next, 8);

CodePudding user response:

head->next = second;

Here second contains garbage. You want

head->next = NULL;

Then second and third variables are not needed. Instead you need to call insertAfter twice to insert 8 and 10.

  • Related