在链表末尾插入

时间:2015-02-22 15:17:14

标签: c linked-list

我正在尝试编写一个创建和显示链接列表的程序,并允许人们在开头,中间或结尾插入元素。

在开头或中间的插入工作完美。但是,我的程序在最后插入时失败了。请看看,告诉我哪里出错或需要修改什么。这是我的代码:

#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;
  }
}

1 个答案:

答案 0 :(得分:3)

列表末尾会发生什么?

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

m->nextNULL时,此检查失败。 NULL->something失败了。所以检查它是否是一个有效的指针,如:

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