简体   繁体   English

C链表节点未存储

[英]C Linked List Nodes Not Storing

This code is supposed to insert a given int after and a given int before a linked list. 该代码应该在链接列表之后插入给定的int,并在链接列表之前插入给定的int。 However, when I pass the arguments in main, they do not store the values in commands insAfter and insBefore, and just return 0. I am guessing it has to do with the integer, but when I had the user input the value in the actual function and set it to the same thing "n" is set to and it worked. 但是,当我在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) ;
  }

}

There's a small mistake in ina() and inb() . ina()inb()有一个小错误。

The statement 该声明

n = temp->data;

should be replaced with 应该替换为

temp->data = n;

Instead of setting the input to the list, you are overwriting n , and not modifying the data of the list node at all. 而不是将输入设置为列表,而是覆盖n ,并且完全不修改列表节点的data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM