C - 链表打印顺序错误

C - Linked list printing in the wrong order

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

    #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;

    }

但是,当我打印链表中的元素时,它们的打印顺序与作为参数输入的顺序相反。我怎样才能按照输入它们的顺序打印它们?我觉得我好像漏掉了一些小东西,但我不知道那是什么。

这是你的问题

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;
}

不要忘记为 free 所有 malloced 内容编写一个 freeList() 函数。

在您的 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
    }


}