如何实现基于命令行参数的链表创建与格式化输出?
解决方案
以下是修改后的完整代码,实现了从命令行参数构建链表并按指定格式输出的功能:
#include <stdlib.h> #include <stdio.h> typedef struct s_list t_list; struct s_list { int value; t_list *next; }; void add_node_end(t_list **head, int value); void add_node_start(t_list **head, int value); int remove_first(t_list **head); int remove_last(t_list *head); int remove_by_index(t_list **head, int n); void print_list(t_list *head); void add_node_end(t_list **head, int value) { t_list *current; // 处理链表为空的情况 if (*head == NULL) { *head = malloc(sizeof(t_list)); (*head)->value = value; (*head)->next = NULL; return; } current = *head; while (current->next != NULL) current = current->next; current->next = malloc(sizeof(t_list)); current->next->value = value; current->next->next = NULL; } void add_node_start(t_list **head, int value) { t_list *new; new = malloc(sizeof(t_list)); new->value = value; new->next = *head; *head = new; } int remove_first(t_list **head) { t_list *next_node; int retvalue; retvalue = -1; next_node = NULL; if (*head == NULL) return (-1); next_node = (*head)->next; retvalue = (*head)->value; free(*head); *head = next_node; return (retvalue); } int remove_last(t_list *head) { t_list *current; int retvalue; retvalue = 0; if (head->next == NULL) { retvalue = head->value; free(head); return (retvalue); } current = head; while (current->next->next != NULL) current = current->next; retvalue = current->next->value; free(current->next); current->next = NULL; return(retvalue); } int remove_by_index(t_list **head, int n) { t_list *current; t_list *temp_node; int retvalue; int i; i = 0; retvalue = -1; if (n == 0) return (remove_first(head)); current = *head; // 初始化current指针,修复未定义行为 while (i < n - 1) { if (current->next == NULL) return (-1); current = current->next; i++; } temp_node = current->next; retvalue = temp_node->value; current->next = temp_node->next; free(temp_node); return(retvalue); } void print_list(t_list *head) { t_list *current; current = head; while (current != NULL) { printf("[%d] ", current->value); // 按指定格式输出 current = current->next; } printf("\n"); // 添加换行符 } int main(int argc, char **argv) { t_list *head; int i; head = NULL; // 检查是否提供了命令行参数 if (argc < 2) { printf("用法: %s <整数1> <整数2> ...\n", argv[0]); return 1; } // 遍历命令行参数,构建链表 for (i = 1; i < argc; i++) { int num = atoi(argv[i]); add_node_end(&head, num); } print_list(head); // 释放链表内存,避免内存泄漏 while (head != NULL) { remove_first(&head); } return 0; }
关键修改点说明:
- 修正
add_node_end函数:新增对空链表的处理逻辑,避免空指针访问错误。 - 修复
remove_by_index函数:初始化current指针为链表头,解决未定义行为问题。 - 调整
print_list函数:修改输出格式为[数值],并在末尾添加换行符。 - 重构
main函数:- 改为接收
argc和argv参数以获取命令行输入。 - 添加参数检查,若未提供参数则输出用法提示。
- 遍历命令行参数,将每个参数转换为整数后添加到链表末尾。
- 程序结束前释放链表内存,防止内存泄漏。
- 改为接收
编译运行示例:
gcc your_file.c -o aout ./aout 20 40 60 80
输出结果:
[20] [40] [60] [80]
内容的提问来源于stack exchange,提问作者Itsme
相关产品推荐
相关产品推荐

