zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第二章 链表问题 两个单链表生成相加链表

    题目

    两个单链表生成相加链表,例如链表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);
        }
    }
    
  • 相关阅读:
    tensorflow笔记1_入门案例
    keras_非线性回归
    python_神经网络识别手写数字0-9
    python_天气查询小程序_1
    打开网站URL遇到“HTTP Error 418:”问题
    笔记1-1三层交换机实现vlan间路由
    用python写一个简单的BP神经网络
    linux系统定时检查网络状态python脚本
    文件名过长,无法删除。
    du 和 df命令
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8729479.html
Copyright © 2011-2022 走看看