首页 > 试题广场 >

链表相加(一)

[编程题]链表相加(一)
  • 热度指数:1590 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个非空链表逆序存储的的非负整数,每个节点只存储一位数组。
请你把两个链表相加以下相同方法返回链表,保证两个数都不会以 0 开头。
数据范围: ,每个节点的值都满足
示例1

输入

{2,5,6},{5,6,1}

输出

{7,1,8}
示例2

输入

{0},{1,2,3,4,5,6}

输出

{1,2,3,4,5,6}
示例3

输入

{9,9,9},{9,9,0}

输出

{8,9,0,1}

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
ListNode res = new ListNode(-1);
        ListNode cur = res;
        int carry = 0;
        while(head1 != null || head2 != null || carry != 0){
            int i = head1 == null ? 0 : head1.val;
            int j = head2 == null ? 0 : head2.val;
            int sum = i + j + carry;
            
            carry = sum / 10;
            ListNode tem = new ListNode(sum % 10);
            
            cur.next = tem;
            cur = cur.next;
            head1 = head1 == null ? null : head1.next;
            head2 = head2 == null ? null : head2.next;
            
        }        
        return res.next;

发表于 2022-04-20 20:01:00 回复(0)