C - 以错误的顺序打印链接列表

时间:2015-01-23 02:12:13

标签: c loops printing linked-list iteration

我创建了一个链表,其元素是从命令行参数获取的字符串:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    struct element_Args {
        char commandLineArgs[500];
    };


    struct list {

    struct element_Args element;
    struct list *next;
    };

    int main(int argc, char *argv[]) {

    struct list *head;
    struct list *current;

    head = (struct list *) malloc(sizeof(struct list));


    head->next = NULL;

    int i;
    for(i = 0; i < argc; i++) {
        current = malloc (sizeof(struct list));
        strcpy(current->element.commandLineArgs, argv[i]);
        current->next = head;
        head = current;

    }

    current = head;

    while(current->next != NULL) {
       printf("%s\n", current->element.commandLineArgs);
       current = current->next;
    }

    return 0;

    }

但是,当我在链表中​​打印元素时,它们将按照与输入参数相反的顺序打印出来。如何按照输入顺序打印它们?我觉得自己好像缺少一些小东西,但我无法弄清楚那是什么。

2 个答案:

答案 0 :(得分:2)

在for循环中,删除head = current

基本上,你使用这条线就会失去对头部的追踪。您可以稍后通过设置临时指针来遍历head,但不要重置head(除非您正在插入新的head)。

要插入一个新头,你会说,newHead->next = head; head = newHead;如果你想按顺序插入它们,你应该保留一个尾指针,并且总是在末尾添加。

int i;
struct list* tail = head;
for(i = 0; i < argc; i++) {
    current = malloc (sizeof(struct list));
    if(current != NULL){
        strcpy(current->element.commandLineArgs, argv[i]);
        tail->next =  current; // add this line
        tail = tail->next;
        current->next = head; //this line makes you add in reverse order. Remove this as well.

        head = current; // remove this line here
    }


}

答案 1 :(得分:0)

这是你的问题

head = current;

你应该让head指向第一个节点,并且永远不要再覆盖它。

因此,在您的代码中,head实际上是tail,因为这些值以相反的顺序打印是合乎逻辑的,它不会反转,您希望它反过来。

试试这个

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct element_Args {
    char commandLineArgs[500];
};


struct list {

struct element_Args element;
struct list *next;
};

int main(int argc, char *argv[]) {
    struct list *head;
    struct list *current;
    struct list *last;
    int i;

    head = malloc(sizeof(*head));
    if (head == NULL)
        return -1;
    head->next = NULL;

    last = head;
    for(i = 0 ; i < argc ; i++) {
        current = malloc (sizeof(*current));
        if (current != NULL) {

            strcpy(current->element.commandLineArgs, argv[i]);

            last->next = current;
            last       = current;
        }
    }

    current = head;
    while(current != NULL) {
        printf("%s\n", current->element.commandLineArgs);
        current = current->next;
    }

    return 0;
}

不要忘记将freeList()功能写入free所有malloc内容。