题解 | 牛牛的单链表求和
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h>
#include <stdlib.h>
// write your code here......
//定义链表结构体
typedef struct Node{
int data;
struct Node* next;
}Node;
//功能:根据一个整数数组创建一个链表
//参数:arr-输入的数组;n-数组的长度
//返回值:创建好的链表的头指针
Node* createListFromArray(int* arr,int n)
{
if(n==0)
{
return NULL;
}
Node* head = NULL;
Node* tail = NULL;
for(int i =0;i<n;i++)
{
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->data=arr[i];
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
tail=newnode;
}else
{
tail->next=newnode;
tail = newnode;
}
}
return head;
}
//功能:遍历链表并计算所有节点值的和
//参数:head
//返回值:节点值的总和
int sumList(Node* head)
{
int sum = 0;
Node* current = head;
while(current!= NULL)
{
sum=sum+current->data;
current=current->next;
}
return sum;
}
//功能:释放整个链表占用的内存
//参数: head_ref - 指向头指针的指针,用于在函数内修改原始头指针
void freelist(Node** head_ref)
{
Node* current = *head_ref;
Node* next_node;
while(current!=NULL)
{
next_node=current->next;
free(current);
current=next_node;
}
*head_ref = NULL;
}
int main() {
int n;
scanf("%d",&n);
int* arr=(int*)malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
// write your code here......
//1.根据数组创建链表
Node* head = createListFromArray(arr, n);
//2.遍历链表并求和
int totalSum = sumList(head);
//3.打印总和
printf("%d\n",totalSum);
free(arr);//释放数组
freelist(&head);
return 0;//释放链表
}
我发现无论是链表求和还是释放链表,里面的判定条件都会有while(current!=NULL)
查看12道真题和解析