C Linked List Nodes Not Storing

孤街浪徒 提交于 2019-12-11 14:45:01

问题


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

}

回答1:


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.



来源:https://stackoverflow.com/questions/47115119/c-linked-list-nodes-not-storing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!