gpt4 book ai didi

C 程序,在遍历 pop 函数的单链表时遇到问题

转载 作者:行者123 更新时间:2023-11-30 17:03:43 25 4
gpt4 key购买 nike

我正在尝试创建一个可以通过推送、弹出和完整功能访问的链接列表。我相信我已经正确创建了推送功能,但我在实现弹出功能时遇到了麻烦。我想我已经找到了错误,我无法用 while 循环遍历链表。

这是我的推送功能:

int push(char x){
if(full() == 1) return 1;
else if(full() == 0){
last = malloc(sizeof(struct Node));
aNode = malloc(sizeof(struct Node));
aNode -> next = anchor;
anchor = aNode;
aNode -> data = x;
last -> data = aNode -> data;
last -> next = aNode -> next;
return 0;
}
else{
aNode = malloc(sizeof(struct Node));
aNode -> next = anchor;
anchor = aNode;
aNode -> data = x;
last -> data = aNode -> data;
last -> next = aNode -> next;
return 0;
}

我的pop函数是:

int pop(){
if(full() == 0) return 0;
else{
curr_ptr = malloc(sizeof(struct Node));
store = malloc(sizeof(struct Node));
curr_ptr = anchor;

while(curr_ptr != NULL){
curr_ptr = curr_ptr -> next;
}

store -> next = '\0';
store -> data = last -> data;
last -> next = curr_ptr -> next;
last -> data = curr_ptr -> data;
free(curr_ptr);
return store -> data;

}

我在 while 循环中遇到段错误。我尝试了另一个 while 循环,它没有导致任何错误,但由于某种原因从未在代码中执行。我在循环中添加了一个 printf 语句,但它从未打印任何内容。该循环是:

    while(curr_ptr -> next != NULL){
curr_ptr = curr_ptr -> next;
}

最佳答案

你永远不会在pop中分配last,但你会循环它。将您的 while(curr_ptr/*...*/ 循环替换为for (last=anchor; last->next; last=last->next); 自动跳转 last 到最后一个列表成员。但你的双免来自

curr_ptr = anchor;
/* ... */
free(curr_ptr);

curr_ptr并不指向malloced内存,而是指向anchor,它很可能是您列表的一部分,不应该释放了。正如 Mike 所说,curr_ptr 应该分配内存,而它只是应该指向列表。实际上没有理由在 pop 函数中分配任何东西!

编辑评论:作为关于列表结构的示例,基于您的示例

struct Node {
char data;
struct Node* next;
};
struct List {
struct Node* head;
struct Node* tail;
};
int push(struct List* L, char c);
int pop(struct List* L);

接下来,您可以基本上定义您的函数(无论完整可能意味着什么)。

int push(struct List* L, char c)
{
if (L->head == NULL) {
L->head = L->tail = malloc(sizeof(struct Node));
L->head->data = x;
} else {
L->tail->next = malloc(sizeof(struct Node));
L->tail = L->tail->next;
L->tail->data = x;
}
return 1;
}
int pop(struct List* L)
{
struct Node* cur = NULL;
if (L->head == NULL) {
return 0; /* nothing to remove */
} else if (L->head == L->tail) {
free(L->head);
L->head = L->tail = NULL; /* the list is empty now */
} else {
for (cur = L->head; cur->next != L->tail; cur = cur->next);
cur->next = NULL;
free(L->tail);
L->tail = cur;
}
return 1;
}

现在您可以开始专门满足您的需求。

关于C 程序,在遍历 pop 函数的单链表时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com