C中的LInked List展平

时间:2011-08-12 21:11:48

标签: c linked-list

我正在编写此代码来练习链接列表。目标是扁平化链表。任何人都可以帮助指出这里的错误吗?感谢。

(LInk flattening theory:像这样的东西: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;
}

2 个答案:

答案 0 :(得分:1)

一个问题是print_list例程假定列表已经是平的。因此,在确定扁平化和非扁平化列表之间的差异时,它不会非常有用。

另一个问题是,当你压扁一个孩子时,你不会使子指针为空。我希望看到像

这样的东西
    if (curNode->child){
        printf("current node has a child\n");
        append(curNode->child,&tail);   
        curNode->child = NULL;
    }

另一个问题是因为你的展平过程将子节点附加到列表的末尾不可避免地重新排序列表。这不是扁平化功能应该是什么。例如,如果你压扁

(1 2(3 4 5)6 7)

然后你应该

(1 2 3 4 5 6 7)

而你的代码(如果我理解的话)会给出

(1 2 6 7 3 4 5)

现在已经够了,祝你好运!

答案 1 :(得分:0)

和其他人一样,我不确定你的问题是什么(你说“扁平”是什么意思?),但这是一个错误:

append(curNode->child,&tail);

应该是

append(curNode->child,tail);
相关问题