如何在C语言中读取两个超过long long范围的大数并存入链表?
C语言读取整行文本并存入链表的实现
1. C语言中替代getline的方法
C语言里可以用fgets()函数实现类似C++ getline()的整行读取功能,它能读取包括换行符在内的整行输入,直到达到指定长度或遇到换行/EOF。
用法示例:
char buffer[100]; // 缓冲区大小根据数字长度调整 // 读取一行到buffer if (fgets(buffer, sizeof(buffer), stdin) != NULL) { // 去掉末尾的换行符(如果存在) size_t len = strlen(buffer); if (len > 0 && buffer[len-1] == '\n') { buffer[len-1] = '\0'; } }
2. 将大数字字符串存入链表的实现
首先定义链表节点结构,每个节点存储一位数字:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> typedef struct Node { int digit; struct Node *next; } Node;
然后实现从字符串创建链表的函数:
Node* createDigitList(const char *numStr) { Node *head = NULL; Node *current = NULL; int len = strlen(numStr); for (int i = 0; i < len; i++) { // 跳过非数字字符 if (!isdigit(numStr[i])) continue; Node *newNode = (Node*)malloc(sizeof(Node)); if (!newNode) { perror("malloc failed"); exit(EXIT_FAILURE); } newNode->digit = numStr[i] - '0'; // 字符转数字 newNode->next = NULL; if (!head) { head = newNode; current = head; } else { current->next = newNode; current = newNode; } } return head; }
3. 完整示例代码
int main() { char num1[100], num2[100]; // 读取第一个大数字 if (fgets(num1, sizeof(num1), stdin) == NULL) { fprintf(stderr, "Failed to read first number\n"); return 1; } size_t len1 = strlen(num1); if (len1 > 0 && num1[len1-1] == '\n') num1[len1-1] = '\0'; // 读取第二个大数字 if (fgets(num2, sizeof(num2), stdin) == NULL) { fprintf(stderr, "Failed to read second number\n"); return 1; } size_t len2 = strlen(num2); if (len2 > 0 && num2[len2-1] == '\n') num2[len2-1] = '\0'; // 创建两个链表 Node *list1 = createDigitList(num1); Node *list2 = createDigitList(num2); // 示例:遍历输出第一个链表的数字 Node *temp = list1; printf("List 1 digits: "); while (temp) { printf("%d ", temp->digit); temp = temp->next; } printf("\n"); // 释放链表内存(避免泄漏) temp = list1; while (temp) { Node *next = temp->next; free(temp); temp = next; } temp = list2; while (temp) { Node *next = temp->next; free(temp); temp = next; } return 0; }
内容的提问来源于stack exchange,提问作者Paul Roman
相关产品推荐
相关产品推荐

