【发布时间】: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