两个单链表生成相加链表

原始题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:
建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面。为了避免两个输入链表同时为空,我们建立一个dummy结点,将两个结点相加生成的新结点按顺序加到dummy结点之后,由于dummy结点本身不能变,所以我们用一个指针cur来指向新链表的最后一个结点。好,可以开始让两个链表相加了,这道题好就好在最低位在链表的开头,所以我们可以在遍历链表的同时按从低到高的顺序直接相加。while循环的条件两个链表中只要有一个不为空行,由于链表可能为空,所以我们在取当前结点值的时候,先判断一下,若为空则取0,否则取结点值。然后把两个结点值相加,同时还要加上进位carry。然后更新carry,直接 sum/10 即可,然后以 sum%10 为值建立一个新结点,连到cur后面,然后cur移动到下一个结点。之后再更新两个结点,若存在,则指向下一个位置。while循环退出之后,最高位的进位问题要最后特殊处理一下,若carry为1,则再建一个值为1的结点,代码如下:

package zuo_chapter2;

public class P66_AddTwoLists {
    public static class Node{
        int val;
        Node next;
        public Node(int val){
            this.val=val;
            this.next=null;
        }
    }
    public static Node addLists(Node l1,Node l2){
        Node dummy=new Node(-1);
        Node cur=dummy;
        int carry=0;
        while (l1!=null||l2!=null){
            int d1=l1!=null?l1.val:0;
            int d2=l2!=null?l2.val:0;
            int sum=d1+d2+carry;
            carry=sum>=10?1:0;
            cur.next=new Node(sum%10);
            cur=cur.next;

            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }
        }
        if(carry==1){
            cur.next=new Node(1);
        }
        return dummy.next;
    }

    public static void printNode(Node head){
        if(head==null)
            System.out.println("no Node!");
        Node cur=head;
        while (cur.next!=null){
            System.out.print(cur.val+"->");
            cur=cur.next;
        }
        System.out.println(cur.val);
    }
    public static void main(String[] args) {
        Node head=new Node(2);
        head.next=new Node(4);
        head.next.next=new Node(3);
        Node head2=new Node(5);
        head2.next=new Node(6);
        head2.next.next=new Node(4);
        printNode(head);//2->4->3
        printNode(head2);//5->6->4
        printNode(addLists(head,head2));//7->0->8
    }
}

参考:Add Two Numbers

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值