问题解决了:)
我希望你能帮助解释我做错了什么。
提前致谢!
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char *data;
struct node * previous;
struct node * next;
} node, *nodePTR;
/* Insert into list */
void insert(char * buf, nodePTR tail) {
nodePTR myNode;
myNode = (node *)malloc(sizeof(node));
myNode->data = malloc(sizeof(char) * 10);
strcpy(myNode->data,buf);
myNode->next = NULL;
myNode->previous = tail;
tail->next = myNode;
//tail = tail->next;
}
void printlist(nodePTR head, int numElements) {
nodePTR tmpNode;
tmpNode = head;
printf("\n\n");
while(tmpNode!=NULL) {
printf("Node data: %s\n", tmpNode->data);
tmpNode = tmpNode->next;
}
}
int main(void) {
/* Variables */
int numElements;
int i;
char buf[10];
nodePTR head, tail;
tail = (node *)malloc(sizeof(node));
head = (node *)malloc(sizeof(node));
tail->data = "EMPTY\0";
tail->next = NULL;
tail->previous = NULL;
head = tail;
printf("Please enter the number of elements:\n");
scanf("%d", &numElements);
/* Build the list */
for(i = 0; i < numElements; i++) {
printf("Please enter the data:");
scanf("%s", buf);
insert(buf, tail);
tail = tail->next;
}
printlist(head, numElements);
return 0;
}
这是我的输出:
请输入元素数量:
3
请输入数据:n1
请输入数据:n2
请输入数据:n3
节点数据:EMPTY
节点数据:n3