C 链表节点不存储

标签 c linked-list

此代码应该在链表之后插入一个给定的 int,在链表之前插入一个给定的 int。但是,当我在 main 中传递参数时,它们不会将值存储在命令 insAfter 和 insBefore 中,而只是返回 0。我猜这与整数有关,但是当我让用户在实际中输入值时函数并将其设置为与“n”相同的值,并且它起作用了。

struct node {
  int data;
  char *item;
  struct node* next;
};

struct node* root = NULL;

void insAfter();
void insBefore();


//Main
void main () {


}



//Command Insert After
void insAfter(int n) {
  struct node* temp;
  temp = (struct node*)malloc(sizeof(struct node));

  n = temp->data;
  temp->next = NULL;

  if(root==NULL) {
    root = temp;
    printf("Text inserted at beginning\n");

  }
  else {
    struct node* p;
    p = root;

    while(p->next != NULL) {
      p = p->next;
    }
    p->next = temp;
      printf("Ok\n");

  }
}

//Command Insert Before
void insBefore(int n) {
  struct node* temp;
  temp = (struct node*)malloc(sizeof(struct node));
  n = temp->data;
  temp->next=NULL;

  if (root == NULL) {
    root = temp;
    printf("Text inserted at beginning\n");
    fflush(stdout);
  }
  else {
    temp->next=root;
    root = temp;
    printf("Ok\n");
    fflush(stdout) ;
  }

}

最佳答案

ina()inb() 有一个小错误。

声明

n = temp->data;

应替换为

temp->data = n;

您不是将输入设置到列表,而是覆盖 n,并且根本不修改列表节点的 data

关于C 链表节点不存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115119/

相关文章:

c - 如何在 C 中合并和排序两个双向链表

c++ - 构造函数从文件中读取并存储在链表中

c - 为什么第一个 gets() 函数不起作用?

c++ - 如何用类实例成员函数指针填充一个函数指针成员?

c++ - 带链表的哈希表,重复节点仍在保存(C++)

c++ - 构建LinkedList时如何调整头尾指针

c++ - 制作链表 C++ 深拷贝的函数

c - 指针分配后错误的结构成员值

c - 矩阵旋转..for循环改变指针的值

c - 如何查找 unsigned char bitmapRep[8192] 中的所有 "1"位?