链接列表 - 命令行参数

Linked List - Command Line arguments

我正在尝试实现一个从命令行构建链表的程序。 我有两个函数,一个创建列表,一个打印它。 我的问题是,从列表中输出数据时,列表的顺序是相反的吗?为什么会这样?我能做什么?提前致谢!

struct      Node {
char*       namePtr_;
struct Node*    nextPtr_;
};

创建列表函数

 struct Node*   makeList    (int argc, char* argv[]) {
 struct Node*   list    = NULL; // Head
 struct Node*   end = NULL; 

if (argc <= 1) {
  return NULL;
}

 int        i;
 for(i = 1;  i < argc;  i++) {
   struct Node* newNode;
   newNode = (struct Node*)malloc(sizeof(list));
   newNode->namePtr_ = argv[i];
   newNode->nextPtr_ = list;
   list = newNode;
 }
  return(list);
}

显示列表函数

void print (const struct Node* list){
    const struct Node*  run;
    run = list;
    while (run != NULL) {
      printf("%s\n", run->namePtr_);
      run = run->nextPtr_;
    }
  }

解除记忆功能

void release (struct Node* list){
  struct Node* head = list;
  free(head);
  free(head->namePtr_);
}

命令行参数

./argList hello there !

输出

!
there
hello

您正在用每个新参数替换列表的头部,从左到右阅读。最后一个参数将是你的最后一个头像。

因此,当您从头向下阅读列表时,最后一个参数将排在第一位,从而反转输入参数。

这里有一个错误

newNode = (struct Node*)malloc(sizeof(list));

sizeof(list) returns一个指针的大小,得到你想要的struct的大小sizeof(*list)

而你在推,而不是你需要入队(附加到尾部,而不是头部)

这里是simple implementation

最后,不要 free(namePtr_),传递给 main (argv[x]) 的参数不是由您的程序动态保留的,规则是每个 free =18=]