C语言 继续打印链表中的最后一个元素



我用c语言创建了一个标准链表,它要求用户输入一个数字,如果用户输入#,则程序结束。如果用户输入其他内容,程序将停止。

问题是我的程序永远运行,首先打印正常列表,然后保持打印链表的最后一个元素。希望有人能告诉我我哪里错了。

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} NodeT;
void freeLL(NodeT *list) {
NodeT *p, *temp;
p = list;
while (p != NULL) {
temp = p->next;
free(p);
p = temp;
}
}
void showLL(NodeT *list) {
NodeT *temp = list;
temp = temp->next;
printf("Done. The list is ");
printf("%d", temp->data);
temp = temp->next;
//iterate the entire linked list and print the data
while (temp != NULL) {
printf("-->");
printf("%d", temp->data);
temp = temp->next; 
}
}
NodeT *joinLL(NodeT *list, int v) {
NodeT *current = list;
NodeT *head;
head->data = v;
head->next = NULL;
while (current->next != NULL) {
current = current->next;
}
current->next = head;
return head;
}
int main() {
int data;
NodeT *list = NULL;
list = (NodeT *)malloc(sizeof(NodeT));
printf("Enter a number: ");
if (scanf("%d", &data) != 1) {
printf("Done. ");
} else {
printf("Enter a number: ");
joinLL(list, data);
while (1 == scanf("%d", &data)) { 
printf("Enter a number: ");
joinLL(list, data);
}
showLL(list);
freeLL(list);
}

return 0;
}

我认为问题在于joinLL函数,它在链表的末尾添加了一个新节点。

问题是你没有在joinLL中分配元素:只有一个元素在main()中分配。

您应该始终分配joinLL中的元素,并从返回值更新head指针。

同理,freeLL也应该将指向head的指针设置为NULL,以保持一致性。

修改后的版本:

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} NodeT;
void freeLL(NodeT *p) {
while (p != NULL) {
NodeT *temp = p->next;
free(p);
p = temp;
}
}
void showLL(const NodeT *list) {
NodeT *p = list;
printf("The list is ");
if (p == NULL) {
printf("empty");
} else {
printf(" %d", temp->data);
while ((p = p->next) != NULL) {
printf("--> %d", temp->data);
}
}
printf("n");
}
NodeT *joinLL(NodeT *head, int v) {
NodeT *newp = malloc(sizeof(*p));
NodeT *current;
if (newp == NULL) {
fprintf(stderr, "allocation failuren");
exit(1);
}
newp->data = v;
newp->next = NULL;
if (head == NULL) {
return newp;
}
for (current = head; current->next != NULL; current = current->next)
continue;
current->next = newp;
return head;
}
int main() {
NodeT *list = NULL;
for (;;) {
int data;
printf("Enter a number: ");
if (scanf("%d", &data) != 1) {
printf("Done. ");
break;
}
list = joinLL(list, data);
}
showLL(list);
freeLL(list);
return 0;
}

程序继续运行,因为内存访问错误,你没有分配内存头(设置一个指针,但直接使用它没有初始化)

这样做可以解决这个问题:

head=(NodeT*)malloc(sizeof(NodeT));
if(NULL==head)
{
// failed : do something...
return NULL;
}
head->data=v;
head->next=NULL;

当我刚刚测试它时,我发现还有一个问题:

list = (NodeT*)malloc(sizeof(NodeT));

malloc不会初始化你的list,所以list->next最初指向的值是不确定的。

c、malloc中的

不需要强制转换

最新更新