c - 创建链表的困难

标签 c algorithm linked-list

在这个程序中,当我创建一个列表时,它会成功创建列表。但是当我尝试打印它时,程序只显示节点的最后两个值。我调试了很多次,发现 (*temp)->next 改变了 start1start2 指针。我无法解决 temp 指针如何更改 start1start2 中的值。

编译器没有产生任何错误或警告。

#include <stdio.h>

struct node {
  int info;
  struct node *next;
} *start1 = NULL, *start2 = NULL;
void create_node(struct node **s1);
void display(struct node **s);

void create_node(struct node **s1)
{
  struct node *ptr = NULL, **temp = s1;
  ptr = (struct node *)malloc(sizeof(struct node));
  if (*s1 == NULL)
  {
    *s1 = ptr;
  } else
  {
    while ((*temp)->next != NULL)
      (*temp) = (*temp)->next;
    (*temp)->next = ptr;
  }
  ptr->next = NULL;
  printf("enter the value\n");
  scanf("%d", &(ptr->info));
}
void display(struct node **s)
{
  struct node **temp = s;
  while ((*temp) != NULL)
  {
    printf("%d\t", (*temp)->info);
    (*temp) = (*temp)->next;

  }
}
void main()
{
  int choice = 0;

  while (1){
    clrscr();
    printf("enter your choice\n");
    printf("enter 1 to create_node1\nenter 2 to create node 2 \nenter 3 to display node 1\nenter 4 to display node2\nenter 5 to exit\n");
    printf("\n");
    scanf("%d", &choice);
    switch (choice)
    {
      case 1:
        create_node(&start1);//correct//
        break;
      case 2:
        create_node(&start2);
        break;
      case 3:
        display(&start1);
        getch();
        break;
      case 4:
        display(&start2);
        getch();
        break;
      case 5:
        exit(1);
        break;
      default:
        printf("invalid");
    }
  }
}

最佳答案

使用这个 while ((*temp)->next != NULL) (*temp) = (*temp)->next;.
这将解决问题。
否则,访问内存不足的索引和程序崩溃。

关于c - 创建链表的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48128113/

相关文章:

algorithm - 修改具有边权重和距离的欧几里德图的星形路由

c++ - G++冒泡排序

algorithm - big-O 表示法是对算法进行最佳、最差和平均情况分析的工具吗?

javascript - 以一种好的方式从链表中删除项目

java - 将两个链表表示的数相加,进位值不传递给下一次计算

c - sizeof 运算符如何在 C 中的 IF 语句中工作

c - `nextafter` 和 `nexttoward` : why this particular interface?

java - 简单 HelloWorld 程序的 JNI : Getting java. lang.UnsatisfiedLinkError

java - 遍历 LinkedList 的最佳方法 - Java

c - 构建文件(Rake 或 Make?)用于构建一些具有通用选项的简单库?