题解 | #牛牛的单链表求和#
牛牛的单链表求和
https://www.nowcoder.com/practice/a674715b6b3845aca0d5009bc27380b5
#include <stdio.h> #include <stdlib.h> typedef struct linklist { int data; struct linklist *next; }linklist; //创建链表节点 linklist *create_node(int x) { linklist *pnew = (linklist*)malloc(sizeof(linklist)); pnew->data = x; pnew->next = NULL; return pnew; } linklist *insert_linklistlist(linklist *head,int data) { linklist *p = head ; linklist *newnode = create_node(data); if( head -> next == NULL) { head -> next = newnode; } else { while ( p -> next != NULL) { p = p -> next; } p -> next = newnode; } return head; } int sum_linklist(linklist *head) { int sum = 0; linklist *p = head->next; while (p != NULL) { sum = sum + p->data; p = p->next; } return sum; } int main() { int n = 0 ; scanf("%d",&n); int arry[n] ; //创建带头节点的链表头节点 linklist *head = (linklist*)malloc(sizeof(linklist)); head->next = NULL; head -> data = 10000; //输入数组,插入节点 for(int i = 0 ; i < n ; i++) { scanf("%d",&arry[i]); head = insert_linklistlist(head,arry[i]); } printf("%d",sum_linklist(head)); }