两数求和(链表)

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
分析:相加的时候按逆序相加,从头结点开始进行相加运算
在这里插入图片描述
数字相加可能会溢出,则需要引入进位,从表头开始加,直到遍历到链表的尾端。每次记得更新进位的值和移动节点的位置。
代码实现:

public class ListNode {
     int value;
      ListNode next;
      ListNode(int x) { value = x; }
  class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int jinwei = 0;  //进位
            int x = 0, y = 0;
            ListNode tempHead = new ListNode(0);  //哑元结点
            ListNode p1 = l1;
            ListNode p2 = l2;
            ListNode currency = tempHead;
            while (p1 != null || p2 != null) {
                if (p1 != null) {
                    x = p1.value;
                } else {
                    x = 0;
                }
                if (p2 != null) {
                    y = p2.value;
                } else {
                    y = 0;
                }
                int result = jinwei + x + y;
                jinwei = result / 10;   //更新进位的值
                currency.next = new ListNode(result % 10);    //新节点(当前的下一个)
                currency=currency.next;
                if (p1 != null) {           //同时往后走
                    p1 = p1.next;
                }
                if (p2 != null) {
                    p2 = p2.next;
                }
            }

            if(jinwei>0){
                currency.next=new ListNode(jinwei);
            }
            return tempHead.next;
        }
    }

每日一练,共勉。

猜你喜欢

转载自blog.csdn.net/weixin_42373873/article/details/90291420
今日推荐