简体   繁体   中英

C Linked List Nodes Not Storing

This code is supposed to insert a given int after and a given int before a linked list. 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.

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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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