gpt4 book ai didi

无法在双向链表中从尾部遍历到头部

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:00 25 4
gpt4 key购买 nike

我已经在 C 中编写了双向链表的代码,它从头到尾遍历良好,但在从尾(尾)到头遍历时,它陷入无限循环并仅打印最后一个的数据只有节点,我不知道出了什么问题。

#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node *prev;
struct node *next;
};
typedef struct node list;

list *head, *current, *newn, *end;

int main() {
int x, y;
current = (list*)malloc(sizeof(list));
printf("enter data:");
scanf("%d", &current->data);

current->next = NULL;
current->prev = NULL;
head = current;
printf("do you want to enter more:");
scanf("%d", &x);
while (x == 1) {
current->next = (list*)malloc(sizeof(list));
printf("enter data:");
scanf("%d", &current->next->data);
current->next->prev = current->next;
current->next->next = NULL;
current = current->next;
end = current;
printf("do yo want to enter more:");
scanf("%d", &x);
}

newn = head;
while (newn != NULL) {
printf("%d:%d:%d->", newn->prev, newn->data, newn->next);
newn = newn->next;
}
while (end->prev != NULL) {
printf("%d", end->data);
end = end->prev;
}
}

最佳答案

将评论的答案放在一起,这里是固定代码:

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
typedef struct node list;
list *head, *current, *newn, *end;

void exitWithFail() {
printf("Error: exiting.\n");
exit(1);
}

int main()
{
int x,y,r;
current = (list*)malloc(sizeof(list));
printf("enter data:");
r = scanf("%d",&current->data);
if (r != 1) exitWithFail();
current->next = NULL;
current->prev = NULL;
head = end = current;
printf("do you want to enter more:");
r = scanf("%d",&x);
if (r != 1) exitWithFail();
while(x == 1)
{
current->next = (list*)malloc(sizeof(list));
printf("enter data:");
r = scanf("%d",&current->next->data);
if (r != 1) exitWithFail();
current->next->prev = current; // problem No.1
current->next->next = NULL;
current = current->next;
end = current;
printf("do yo want to enter more:");
r = scanf("%d",&x);
if (r != 1) exitWithFail();
}
newn = head;

while(newn != NULL)
{
printf("%d ",newn->data);
newn = newn->next;
}
printf("\n");
while(end != NULL) // Problem No. 2
{
printf("%d ",end->data);
end = end->prev;
}
printf("\n");
}

关于无法在双向链表中从尾部遍历到头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769654/

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