题解 | #牛牛的单链表求和#

牛牛的单链表求和

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));
}

全部评论

相关推荐

鼠鼠求offer鸭:没事,骗一次就老实不会幻想有好事砸中自己了😂😂
点赞 评论 收藏
分享
不如似了得了:淘天秒挂,原来是面试官在救我,令人暖心🥺
投递淘天集团等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务