• 《程序员代码面试指南》第二章 链表问题 两个单链表生成相加链表


    题目

    两个单链表生成相加链表,例如链表1-2-3 加 8-7-7 生成1-0-0-0
    

    java代码

    /**
     * @Description:两个单链表生成相加链表
     * @Author: lizhouwei
     * @CreateDate: 2018/4/6 23:23
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter2_10 {
    
        public Node addLind(Node head1, Node head2) {
            head1 = reverseLink(head1);
            head2 = reverseLink(head2);
            int n1 = 0;
            int n2 = 0;
            int n = 0;
            int ca = 0;
            Node node = null;
            Node head = null;
            Node head1R = head1;
            Node head2R = head2;
    
            while (head1R != null || head2R != null) {
                n1 = head1R == null ? 0 : head1R.vlaue;
                n2 = head2R == null ? 0 : head2R.vlaue;
                n = n1 + n2 + ca;
                head = new Node(n % 10);
                head.next = node;
                node = head;
                ca = n / 10;
                head1R = head1R.next;
                head2R = head2R.next;
            }
            if (ca != 0) {
                head = new Node(ca);
                head.next = node;
            }
            //复原
            head1 = reverseLink(head1);
            head2 = reverseLink(head2);
            return head;
        }
    
        public Node reverseLink(Node head) {
            Node pre = null;
            Node next = null;
            while (head != null) {
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            return pre;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter2_10 chapter = new Chapter2_10();
            Link link1 = new Link();
            Link link2 = new Link();
            link1.add(3);
            link1.add(2);
            link1.add(1);
            link2.add(7);
            link2.add(7);
            link2.add(8);
    
    
            Link.printLink(link1.head);
            Link.printLink(link2.head);
    
            Node head = chapter.addLind(link1.head, link2.head);
            Link.printLink(head);
        }
    }
    
  • 相关阅读:
    xunsearch 在 window 下测试实践(2)
    xunsearch 在 window 下测试实践(1)
    PHPExcel 读取excel文档单元格的值时出现多种字体的解决方法
    laravel session丢失问题
    php多进程批量处理任务
    idea系列产品破解
    lnmp1.4环境下phpinfo扩展缺失解决方法
    从今天开始培养我的写作能力
    go map底层实现
    go之cron使用
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8729479.html
走看看 - 开发者的网上家园