【问题标题】:C Linked List Nodes Not StoringC链表节点不存储
【发布时间】:2017-11-04 20:07:29
【问题描述】:

这段代码应该在链表之后插入给定的 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) ;
  }

}

【问题讨论】:

  • scanf("%s",&command) 应替换为 scanf("%s",command)This 可能会有所帮助。
  • 使用char command[4]; 后跟scanf("%s", &command);(应该是scanf("%s", command);)你是在为这么小的数组和没有输入长度限制而自找麻烦。
  • 在发帖之前,你真的应该做更多的调试。

标签: c linked-list


【解决方案1】:

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

声明

n = temp->data;

应该替换为

temp->data = n;

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

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2019-04-26
    相关资源
    最近更新 更多