我在寫這段代碼來練習鏈表。目標是將鏈表弄平。任何人都可以幫助指出這裏的錯誤嗎?謝謝。在L列表中展平C
(鏈接扁平化理論:事情是這樣的:HTTP://code-forum.blogspot.com/2010/12/function-to-flatten-list-into-single.html)
#include <stdio.h>
typedef struct Node {
struct Node *next;
struct Node *prev;
struct Node *child;
int value;
} Node;
void print_list(Node* root) {
while (root) {
printf("%c ", root->value);
if(root->child){
printf("%c ", root->child->value);
}
root = root->next;
}
printf("\n");
}
void append(Node *child, Node **tail){
Node *curNode = child;
(*tail)->next = curNode;
curNode->prev = *tail;
*tail = curNode;
}
void flatten_list(Node *head, Node **tail) {
printf("in flatten function now\n");
Node *curNode = head;
while (curNode) {
if (curNode->child){
printf("current node has a child\n");
append(curNode->child,tail);
curNode->child= NULL;
}
curNode = curNode->next;
}
}
main()
{
Node g = { 0, 0, 0, '1' };
Node e = { 0, 0, 0, '9' };
// Node f = { 0, &e, 0, '8' };
Node d = { 0, 0, 0, '6' };
Node c = { &d, 0, &g ,'5' };
Node b = { &c, 0, 0 , '3' };
Node a = { &b, 0, &e, '4' };
Node* root = &a;
Node *tail = &g;
printf("Unflattened List:\n");
print_list(root);
flatten_list(root,&tail);
printf("Flattened List:\n");
print_list(root);
return 0;
}
除非你告訴我們症狀,可能不是。 –
in'void flatten_list(Node * head,Node ** tail)':if head == 0:curNode = 0; while(0)nothing; curNode = 0-> next // bad – all
另外,在調用'append()'和'curNode = curNode-> next之間放置curNode-> child = 0; ' – all