这段代码在将节点插入到NULL单元格时工作正常。我尝试将其实现为将单元格发送到开头,但自那以后,display_list函数只显示最后一个单元格。我已经试图找出原因一段时间了,有什么建议吗?
我会补充说明,这应该是一个模仿Linux中的dc函数的函数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct CELL {
int val;
struct CELL *next;
};
void append_node(struct CELL *llist, int num);
void display_list(struct CELL *llist);
主要看起来很好
int main(void)
{
int num = 0;
int first = 0;
int input = 0;
char quit = 'n';
char inputchar = ' ';
struct CELL *llist;
llist = (struct CELL *)malloc(sizeof(struct CELL));
llist->next = NULL;
while (quit == 'n'){
if (scanf("%d", &input) == 1){
if ( first == 1 )
append_node(llist, input);
if ( first == 0){
llist->val = input;
first = 1;
}
}
else{
inputchar = getchar();
if (llist->next == NULL && first == 0)
printf("List is empty.\n");
if (inputchar == 'f')
display_list(llist);
if (inputchar == 'q')
quit = 'y';
else if (llist->next != NULL){
switch (inputchar){
case 'q':
quit = 'y';
break;
}
}
}
}
free(llist);
return 0;
}
这段被注释的代码是正常工作的!但是我发现我应该将单元格添加到另一端,而我很难想出如何实现。我在这里错过了什么?
void append_node(struct CELL *llist, int num) {
/* while(llist->next != NULL)
llist = llist->next;
llist->next = (struct CELL *)malloc(sizeof(struct CELL));
llist->next->val = num;
llist->next->next = NULL;*/
struct CELL *temp;
temp = (struct CELL *)malloc(sizeof(struct CELL));
temp->val = num;
temp->next = llist;
llist = temp;
}
void display_list(struct CELL *llist)
{
while(llist->next != NULL) {
printf("%d\n", llist->val);
llist = llist->next;
}
printf("%d\n", llist->val);
}
我承认我不太清楚何时应该使用指针,我怀疑可能有地方遗漏了。希望能得到帮助。
cell
结构,而是取代客户端将要访问的内容。客户端不应该知道cell
结构的存在。 - GhazanfarLinkedList
结构。现在,主函数将创建该结构的实例,而不是cell
的实例。现在,您所有的add
、delete
和display
函数都将接受这个LinkedList
结构,而不是cell
。 - Ghazanfar