题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; } node, *nptr; //创建链表 void create_Node(nptr headpin, int value) { nptr newnode = (nptr)malloc(sizeof(node));//创建新节点,返回指向新节点的指针 if (newnode == NULL) { return; // 内存分配失败,处理错误 } newnode->data = value; newnode->next = headpin->next; headpin->next = newnode; } //释放内存 void freelinks(nptr h) { nptr c = h; while (c != NULL) { nptr temp = c; c = c->next; free(temp); } } //计算器 int calculateSum(nptr h) { int sum = 0; nptr current = h->next;//新创建一个指针指向哨兵节点后一个节点(也即第一个真正包含值的创建的节点) while (current != NULL) { sum += current->data; current = current->next;//将指针不断往后,除非遇到NULL否则不会停下 } return sum; } int main() { node head = {0, NULL};//创建哨兵节点 nptr h = &head;//初始化指向哨兵节点的指针,用来记录哨兵节点的位置 nptr headpin = &head;//再初始化一个指向哨兵节点的指针,用来移动并创建新节点 int n; int s; //链表(当然你也可以在for中,一边创建数组的同时一边创建链表) scanf("%d", &n); for (int i = 0; i < n; i ++) { scanf("%d", &s); create_Node(headpin, s); } // 计算和 int sum = calculateSum(h); printf("%d", sum); //释放内存 freelinks(head.next); return 0; }