我创建了一个链表,其元素是从命令行参数获取的字符串:
#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("%sn", current->element.commandLineArgs);
current = current->next;
}
return 0;
}
但是,当我打印链表中的元素时,它们以与输入参数的顺序相反的方式打印出来。 如何按照输入时的顺序打印它们? 我觉得我好像错过了一些小东西,但我无法弄清楚那是什么。
在 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
}
}
你的问题
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("%sn", current->element.commandLineArgs);
current = current->next;
}
return 0;
}
不要忘记编写一个freeList()
函数来free
所有malloc
编辑的内容。