gpt4 book ai didi

c - 反向打印双向链表

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

我有一个可以从上到下打印的双向链表,现在我正尝试从下到上打印它。

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

//defines the struct UserData
typedef struct
{
int importance;
char taskName[80];
}UserData, *UserDataPtr;

//Defines a node
typedef struct node {
UserData Data;
struct node *next;
struct node *prev;
} Node, *NodePtr;

NodePtr makeNode(UserData);

//Declare function printList
void printList(NodePtr);

void printListRev(NodePtr);

int main()
{
UserData info;
NodePtr top, ptr, last, temp;



top = NULL;

FILE *filein=fopen("Data.txt", "r");
if (filein == NULL) {
printf("Error opening file, exiting program.\n");
exit(0);
}

while(fscanf(filein, "%d%s",&info.importance, info.taskName)==2)
{
ptr=makeNode(info);
if (top == NULL) top = ptr;
else last -> next = ptr;
last = ptr;
}//end while loop

printList(top);


printListRev(last);
}//end Main


//printList is a function that prints each node as long as it isn't NULL. Once it reaches NULL it terminates, signifying the end of the list.
void printList(NodePtr ptr) {
while (ptr != NULL) { //as long as there's a node
printf("%d %s\n", ptr -> Data.importance, ptr -> Data.taskName);
ptr = ptr -> next; //go on to the next node

}
if (ptr == NULL) {

printf("Last node data printed moving forward.\n");
}

} //end printList


void printListRev(NodePtr ptr) {
while(ptr != NULL){
printf("%d %s\n", ptr -> Data.importance, ptr -> Data.taskName);
ptr = ptr -> prev;


}
}//end printListRev

//Define function makeNode. Allocates storage for node, stores integer given to it, and returns a pointer to the new node. Also sets next field to NULL
NodePtr makeNode(UserData info) {
NodePtr ptr = (NodePtr) malloc(sizeof (Node));
ptr -> Data = info;
ptr -> next = NULL;
ptr -> prev = NULL;
return ptr;
} //End makeNode

这是输出:

1 task1
2 task2A
3 task3A
2 task2B
4 task4A
4 task4B
3 task3B
Last node data printed moving forward.
3 task3B

而且我不知道为什么它不会反向打印完整列表。反向打印时只打印一项。

直到“打印的最后一个节点数据”消息都是正确的。是的,它有点乱,我是 C 的新手,我需要清理我的评论等等。抱歉。

有人能帮忙吗?

最佳答案

将节点插入列表时,您忘记将 prev 字段设置为适当的值。修复很简单:将 last 初始化为 NULL,然后在 ptr = makeNode(信息);

顺便说一下,temp 没有被使用。

关于c - 反向打印双向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39554044/

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