初始化C中的双向链表,指针

时间:2017-01-29 18:36:30

标签: c list pointers

是否可以在一行代码中启动* before和* next的值?

这是我得到的错误:

$ gcc test.c -std=c99
test.c: In function ‘main’:
test.c:34:10: error: expected expression before ‘{’ token
     n3 = { .value = 300, .preceding = &n2, .next = tail };
          ^
test.c:35:10: error: expected expression before ‘{’ token
     n2 = { .value = 200, .preceding = &n1, .next = &n3 };
          ^
test.c:36:10: error: expected expression before ‘{’ token
     n1 = { .value = 100, .preceding = &header, .next = &n2 };
          ^
test.c:37:14: error: expected expression before ‘{’ token
     header = { .next = &n1 };

或者我需要分别发起.previous.next

list_pointer = &header的{​​{1}}列表.next = tail中设置turn tail = (struct entry *) 0和最后一个元素是否正确?还是有更方便的方法?

 // Prints out the elements of the doubly linked  list, from head to tail and backwards.

#include <stdio.h>

struct entry
{
    int            value;
    struct entry   *preceding;
    struct entry   *next;
};

void printPlist(struct entry *list)
{
    list = list->next; // switch from header(start of the list) to n1; because !(header.value) or NULL

    while (list->next) {
        printf("%i\n", list->value);
        list = list->next;
    }

    printf("\n");

    while (list->preceding) {
        printf("%i\n", list->value);
        list = list->preceding;
    }
    printf("\n");
}

int main(void)
{
    struct entry *tail = (struct entry *) 0;
    struct entry header, n1, n2, n3;
    n3 = { .value = 300, .preceding = &n2, .next = tail };
    n2 = { .value = 200, .preceding = &n1, .next = &n3 };
    n1 = { .value = 100, .preceding = &header, .next = &n2 };
    header = { .next = &n1 };
    struct entry *list_pointer = &header;

    printPlist(list_pointer);  // from head to tail and backwards.

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您无法使用designated initializers重新初始化现有对象。

您也不能使用它们来创建来初始化整个列表,因为创建对象时,对以下节点的必需引用尚不存在。

因此我建议添加另一个函数来在创建条目后对其进行初始化。 (或者另一个,也使用malloc为您创建条目。)

见这个例子:

void initializeEntry(struct entry *this, 
                     int value,
                     struct entry *preceding,
                     struct entry *next)
{
    this->value = value;
    this->preceding = preceding;
    this->next = next;
}

int main()
{
    // declare (and create) the list element objects
    struct entry header, n1, n2, n3;

    // initialize the list elements
    initializeEntry(&header, 0, 0, &n1);
    initializeEntry(&n1, 100, &header, &n2);
    initializeEntry(&n2, 200, &n1, &n3);
    initializeEntry(&n3, 300, &n2, 0);

    // print the list
    printPlist(&header);

    return 0;
}

答案 1 :(得分:1)

您可以在一行中定义两个链接。

struct entry
{
    int            value;
    struct entry   *preceding, *next;
};

您可以使用预处理器宏使初始化非常简洁方便。

int main() {

    typedef struct LinkedList {
        struct LinkedList   *prev, *next;
        int value;
    } linkedList_t;

    linkedList_t head =  { &head, &head, 0 };
}

ulist.h是您可以在整个程序中使用的C链接列表宏的众多示例之一。让生活变得更轻松,我在代码商店工作,他们在整个产品中使用这样的宏,使产品可读,更容易编写,更一致,更易于理解和维护。