两个链表相加

这篇博客详细介绍了如何实现两个链表相加的算法。通过计算每个节点的值和进位,逐步遍历并更新链表,确保较短的链表在前,最后处理可能的进位。该算法涉及链表操作和进位逻辑,是数据结构和算法的经典问题。

啥意思:计算加法:比如:9->9->9->9 + 1->9->7 = 0->9->7->0->1
精髓:就是抠好链表的长度,找出谁是长链表,因为长链表肯定得留到最后

/**
 * 两个链表相加
 */
public class Code06 {
    public static class Node<V> {
        public V value;
        public Node<V> last;
        public Node<V> next;
        public Node() {
        }
        public Node(V v) {
            value = v;
            last = null;
            next = null;
        }
    }
    public static void print(Node head){
        while (head != null){
            System.out.print(head.value+" ");
            head = head.next;
        }
    }


    public static void main(String[] args) {
        Node node1 = new Node(9);
        Node node2 = new Node(9);
        Node node3 = new Node(9);
        Node node4 = new Node(9);

        Node node5 = new Node(1);
        Node node6 = new Node(9);
        Node node7 = new Node(7);

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

        node5.next = node6;
        node6.next = node7;
        Node ret = addLinkList(node1,node5);
        print(ret);
    }
    private static int length(Node node){
        int length = 0;
        while (node != null){
            length++;
            node = node.next;
        }
        return length;
    }
    private static Node<Integer> addLinkList(Node<Integer> node1, Node<Integer> node2) {
        int len1 = length(node1);
        int len2 = length(node2);
        Node<Integer> l = len1 >= len2 ? node1 : node2;
        Node<Integer> s = l==node1 ? node2 : node1;
        Node<Integer> curL = l;
        Node<Integer> curS = s;
        // 进位信息
        int carrayNum = 0;
        Node<Integer> cur = curL;
        while (curS != null){
            int num = curL.value+curS.value+carrayNum;
            int yu = num%10;
            int shang = num/10;
            curL.value = yu;
            carrayNum = shang;
            cur = curL;
            curL = curL.next;
            curS = curS.next;
        }
        while (curL != null){
            int num = curL.value+carrayNum;
            int yu = num%10;
            int shang = num/10;
            curL.value = yu;
            carrayNum = shang;
            cur = curL;
            curL = curL.next;
        }
        if(carrayNum>0){
            Node<Integer> end = new Node<>(carrayNum);
            cur.next = end;
        }
        return l;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值