按正确的顺序打印链接列表

时间:2014-11-08 20:10:32

标签: c printing linked-list

我正在尝试打印我在C中创建的链接列表,但它打印的顺序错误,我无法理解原因。我正确分配指针。有人可以帮我吗?这是我的代码:

struct list_el {
    int val;
    struct list_el * next;
};

typedef struct list_el item;

void main() {
    item *curr, *head;
    int value;
    head = NULL;

    scanf("%d", &value);

    while (value != 0){
        scanf("%d", &value);
        curr = (item *)malloc(sizeof(item));
        curr->val = value;
        curr->next = head;
        head = curr;
}
    curr = head;

    while (curr) {
        printf("%d\n", curr->val);
        curr=curr->next;
    }
    return 0;
}

3 个答案:

答案 0 :(得分:1)

scanf("%d", &value);

while (value != 0){
    curr = (item *)malloc(sizeof(item));
    curr->val = value;
    curr->next = head;
    head = curr;
    scanf("%d", &value);
}

答案 1 :(得分:1)

如果您希望列表与输入的顺序相同,则需要附加到列表的末尾(尾部)。

int main() {
    item *curr, *head, *tail;
    int value;
    head = NULL;

    scanf("%d", &value);

    while (value != 0) {
        curr = (item *)malloc(sizeof(item));
        curr->val = value;
        curr->next = NULL;
        if (head == NULL) {
           head = tail = curr;
        } else {
           tail->next = curr;
           tail = curr; 
        }
        scanf("%d", &value);
     }

     ...
}

答案 2 :(得分:0)

尝试以下方法。在列表中创建一个虚拟节点,以避免明确处理极端情况(空列表等)。

int main() {
    item *curr, *head;
    int value=-1;
    head = (item *)malloc(sizeof(item));
    curr = head;

    while (value != 0){
        scanf("%d", &value);
        curr->val = value;
        curr->next = (item *)malloc(sizeof(item));
        curr = curr->next;
    }
    curr = head;

    while (curr->next) {
        printf("%d\n", curr->val);
        curr=curr->next;
    }
    return 0;
}

给出

$ ./a.out 
1
2
3
4
5
0
1
2
3
4
5
0