链表节点加法

链表有序递增,每个节点都是0-9内的数字,相加的时候涉及进位问题,如:

链表1:

123

链表2:

789

结果链表:

81012

思路:同时遍历2个链表,计算2个链表同一位置的节点之和,判断是否<10,如果小于不进位,直接new个node节点

如果>10 那么涉及进位问题,需要前插进位的1节点,next节点为和10取余

/**
 * @author yuchen
 * @version 1.0
 * @date 2020-05-26 11:20
 */
public class NodePlus {

    public static void main(String[] args) {

        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        node1.next = node2;
        node2.next = node3;

        Node node7 = new Node(7);
        Node node8 = new Node(8);
        Node node9 = new Node(9);

        node7.next = node8;
        node8.next = node9;

        Node node = plusNode(node1,node7);
        while (node!=null){
            System.out.println(node.data);
            node = node.next;
        }
    }

    static class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }

    public static Node plusNode(Node head1,Node head2){

        if(head1==null && head2!=null){
            return head2;
        }

        if(head2==null && head1!=null){
            return head1;
        }

        int jinwei = 0;
        Node cur1Node = head1;
        Node cur2Node = head2;
        Node pre = null;

        while (cur1Node!=null){
            cur1Node.data += jinwei;
            if(cur2Node!=null){
                cur1Node.data = cur1Node.data + cur2Node.data;
                cur2Node = cur2Node.next;
            }

            jinwei = cur1Node.data / 10;
            cur1Node.data = cur1Node.data % 10;
            pre = cur1Node;
            cur1Node = cur1Node.next;
        }

        while (cur2Node!=null){
            cur2Node.data += jinwei;
            jinwei = cur2Node.data / 10;
            cur2Node.data = cur2Node.data % 10;
            pre.next = cur2Node;
            pre = pre.next;
            cur2Node = cur2Node.next;
        }

        if (jinwei > 0){
            Node node = new Node(jinwei);
            pre.next = node;
        }

        return head1;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值