zoukankan      html  css  js  c++  java
  • 两数相加 Java链表实现

    定义节点

    public class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int x){
            this.val = x;
        }
    }

    两数相加

    public class AddTwoNums {
    
        public static void main(String[] args){
            ListNode l1 = new ListNode(5);
            ListNode l2 = new ListNode(5);
            l1.next = new ListNode(4);
            l1.next.next = new ListNode(3);
            l2.next = new ListNode(6);
            l2.next.next = new ListNode(4);
            l2.next.next.next = new ListNode(1);
            l2.next.next.next.next = new ListNode(2);
            print(l1);
            print(l2);
            AddTwoNums addTwoNums = new AddTwoNums();
    
            print(addTwoNums.addTwoNumbers(l1,l2));
    
        }
    
        public ListNode addTwoNumbers(ListNode l1,ListNode l2){
            ListNode targetList = new ListNode(0);
            ListNode p = l1;
            ListNode q = l2;
            ListNode current = targetList;
            while(p != null || q != null){
                int x = 0,y = 0,sum;
                if (p != null) {
                    x = p.val;
                    p = p.next;
                }
                if (q != null) {
                    y = q.val;
                    q = q.next;
                }
                sum = x+y+current.val;
                int carry = sum/10;
                int reminder = sum%10;
                current.val = reminder;
                current.next = new ListNode(carry);
                current = current.next;
            }
            current  = targetList;
            while (current.next.next != null){
                current = current.next;
            }
            if (current.next.val == 0)
                current.next = null;
            return targetList;
        }
    
        /**
         * 遍历list
         * @param listNode
         * @return
         */
        public static ListNode print(ListNode listNode){
            if (listNode != null) {
                System.out.print(listNode.val +"->");
                return print(listNode.next);
            }
            else{
                System.out.println("NULL");
                return null;
            }
        }
    }
    
  • 相关阅读:
    webpack学习(一)—— 入门
    AMD 规范
    CommonJS 规范
    webpack 故障处理
    webpack 开发环境
    webpack 插件
    webpack 配置文件
    webpack 使用
    webpack Loader
    webpack常用的插件安装命令
  • 原文地址:https://www.cnblogs.com/outxiao/p/12778908.html
Copyright © 2011-2022 走看看