【发布时间】:2016-09-18 04:18:32
【问题描述】:
我有一个可以从上到下打印的双向链表,现在我正在尝试从下到上打印它。
#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 新手,我需要清理我的 cmets 等。道歉。
谁能帮忙?
【问题讨论】:
-
请注意,点
.和箭头->操作符绑定得非常紧密,绝对不能在它们周围写上空格。 (是的,它在语法上是有效的;您可以将它们放在与结构/指针和成员名称不同的行上,它会编译。这是一个正常或传统表示的问题——C 和 C++ 的编写方式。)跨度> -
在读取阶段,您设置了
last->next,但您从未将任何prev成员设置为NULL 以外的任何值。在向前打印列表时,您应该使用%p格式打印地址(next和prev成员);您会在next值中看到太多空指针。
标签: c