美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: 西土城小羊 | 来源:发表于2017-03-09 10:48 被阅读13次

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    读题

    题目的意思是说,给定两个非空的链表,计算两个链表所表示数的和,返回一个结果的链表,其实可以看出来就是一个大数相加的思想

    题解

    public class Solution2 {
        public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode p1 = l1;
            ListNode p2 = l2;
            //表示进位数
            int jinwei = 0;
            ListNode result = new ListNode(0);
            
            //指向结果的node
            ListNode head = result;
            //当前计算节点的前一个节点引用
            ListNode pre = result;
            int a;
            int b;
            while(p1!=null||p2!=null||jinwei!=0){
                //如果节点的是空加数为0否则为节点的值
                a = (p1 == null?0:p1.val);
                b = (p2 == null?0:p2.val);
                //计算进位数和本位和
                result.val = (a + b +jinwei)%10;
                jinwei = (a + b +jinwei)/10;
                //将pre应用指向当前的计算节点
                pre = result;
                //创建一个新的节点result向后移动
                ListNode p = new ListNode(0);
                result.next = p;
                result = p;
                if(p1!=null)
                    p1 = p1.next;
                if(p2!=null)
                    p2 = p2.next;
            }
            //pre最终指向最后一个节点
            pre.next = null;
            return head;
        }
    
        public static void print(ListNode p) {
            while (p != null) {
                System.out.print(p.val);
                p = p.next;
                if (p != null) {
                    System.out.print(" -> ");
                }
            }
        }
    
        public static void main(String[] args) {
            ListNode node1 = new ListNode(1);
            ListNode node2 = new ListNode(2);
            ListNode node3 = new ListNode(3);
            node1.next = node2;
            node2.next = node3;
            node3.next = null;
            
            ListNode node4 = new ListNode(2);
            ListNode node5 = new ListNode(1);
            ListNode node6 = new ListNode(7);
            node4.next = node5;
            node5.next = node6;
            node6.next = null;
            //Solution2.print(node1);
            Solution2.print(Solution2.addTwoNumbers(node1, node4));
        }
    }
    

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

          本文链接:https://www.haomeiwen.com/subject/hfcbwttx.html