user3502675
user3502675

Reputation:

Insertion at end of linked list

I am trying to write a program that creates and displays linked lists, and allows people to insert an element at the beginning, middle or end.

Insertion at the beginning or the middle works perfectly. However, my program fails when it comes to inserting at the end. Please have a look and tell me where I am going wrong or what needs modification. Here is my code:

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

struct node {
  int number;
  struct node *next;
};

typedef struct node NODE;
NODE *node1, *start, *rear, *m, *nodex, *temp1;

int main() {
  int i, n1, n2;
  start = NULL;
  printf("Enter the number of inputs to the list:");
  scanf("%d", &n1);

  for (i = 0; i < n1; i++) {
    // node creation begins here
    node1 = (NODE*) malloc(sizeof(NODE));
    int inf;
    printf("Enter node value:");
    scanf("%d", &inf);
    node1->number = inf;
    node1->next = NULL;

    if (start == NULL) {
      // first node creation
      start = rear = node1;
    } else {
      m = start;
      if (m->number > inf) {
        // for insertion in beginning
        node1->next = m;
        start = node1;
      } else {
        while (m->next->number < inf) {
          // searching to insert in middle of sorted list
          m = m->next;
        }
        temp1 = m->next;
        m->next = node1;
        node1->next = temp1;
      }
    }
    display(); // to display the linked list
  }
  return 0;
}

void display() {
  nodex = start;
  while (nodex != NULL) {
    printf("%d ->", nodex->number);
    nodex = nodex->next;
  }
}

Upvotes: 0

Views: 97

Answers (1)

ninja
ninja

Reputation: 809

What happens at the end of the list?

while(m->next->number < inf){
    //searching to insert in middle of sorted list 
    m=m->next;
}

This check fails when m->next is NULL. NULL->something fails. So do a check if it's a valid pointer, like:

while(m->next)
    if(m->next->number < inf)
        m=m->next;
    else
        break;

Upvotes: 3

Related Questions