题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

/**
 思路:
 1. 先将链表逆序
 2. 然后将各个节点值相加
 3. 遍历链表大于10的减去10,向下个节点进一
 4. 再次将链表逆序
**/
#include <stdio.h>
#include <stdlib.h>
int countList(struct ListNode* head)
{// 统计链表长度
    int cnt = 0;
    while (head) {
        head = head->next;
        cnt++;
    }
    return cnt;
}
struct ListNode* reverse(struct ListNode* head)
{// 将链表逆序
    struct ListNode *p = NULL;
    struct ListNode *q = NULL;
    if(!head || !head->next)
    {
        return head;
    }
    p = head;
    q = head->next;
    head->next = NULL;
    while (p) {
        p = q->next;
        q->next = head;
        head = q;
        q = p;
    
    }
    return head;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {

    int cnt1 = countList(head1);
    int cnt2 = countList(head2);

    head1 = reverse(head1);
    head2 = reverse(head2);

    struct ListNode* t1 = NULL;
    struct ListNode* t2 = NULL;
    struct ListNode* head = NULL;
    if(cnt1>cnt2)
    {
        head = head1;
        t1 = head1;
        t2 = head2;
    }
    else {
        head = head2;
        t1 = head2;
        t2 = head1;
    }
    while (t1) {
        if(t2){
            t1->val = t1->val + t2->val;
            t1 = t1->next;
        }
        else {
            t1 = t1->next;
            break;
        }
        t2 = t2->next;
    }
    t1 = head;
    int flag = 0;
    int pre_flag = 0;
    int val = 0;
    while(t1)
    {
        val = t1->val + pre_flag;
        if(val>=10)
        {
            flag = 1;
        }
        else
        {
            flag = 0;
        }
        t1->val = val - (flag * 10) ;
        if(val>=10)
        {
            pre_flag = 1;
        }
        else
        {
            pre_flag = 0;
        }
        t1 = t1->next;
    }
    head = reverse(head);
    if(pre_flag)
    {
        struct ListNode * node = (struct ListNode *)malloc(sizeof(struct ListNode *));
        node->val = 1;
        node->next = head;
        head = node;
    }
    
    
    return head;
    
}

全部评论
链表长度的统计可以用一个变量来代替,不需要遍历整个链表,这个是不是更好一点?
点赞 回复 分享
发布于 2023-05-25 21:09 江苏
uu你的思路很清晰,代码也很简洁易懂哎!
点赞 回复 分享
发布于 2023-05-25 21:03 天津

相关推荐

就前几天旅游的时候,打开抖音就经常刷到这类视频:以前是高学历学生、老师、主持人,现在做着团播、擦边主播的工作,以及那些经过精心包装的“职业转型”故事——从铺天盖地的VLOG到所谓的“04年夜场工作日记”,这些内容在初中升学、高考放榜等关键时间节点持续发酵。可以说非常直接且精准地在潜移默化地影响着心智尚未成熟的青少年,使其对特殊行业逐渐脱敏。那我就想问了:某些传播公司、平台运营者甚至某些夜场的老板,你们究竟在传递怎样的价值观?点开那些视频,评论区里也是呈现明显的两极分化:一种是​​经济下行论​​:“现在就业市场已经艰难到这种程度了吗?”​​一种是事实反驳派​​:这些创作者往往拥有名校背景,从事着...
牛客刘北:被环境教育的,为了能拿到足够的钱养活自己,不甘心也得甘心,现在的短视频传播的思想的确很扭曲,但是很明显,互联网玩上一年你就能全款提A6,但你全心全意不吃不喝工作一年未必能提A6,但是在高考中考出现这个的确很扭曲,在向大家传播“不上学,玩互联网也可以轻松年入百万”,不是人变了,是社会在变
预测一下26届秋招形势
点赞 评论 收藏
分享
牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
码农索隆:这种hr,建议全中国推广
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务