leetcode__02

来源:互联网 发布:淘宝上好的家具店 编辑:程序博客网 时间:2024/06/05 04:53

题目描述

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

class ListNode{    int value;    ListNode next;    ListNode(int value){        this.value = value;    }}public class AddTwoNumbers {    public  static ListNode addTwoNumbers(ListNode l1,ListNode l2){        ListNode newListNode = new ListNode(0);        int tag = 0;        ListNode p = l1, q = l2,curr = newListNode;        while (p != null || q != null) {            int x = (p != null)? p.value:0;            int y = (q != null)? q.value:0;            int sum = tag+x+y;            tag = sum/10;            curr.next = new ListNode(sum %10);            curr = curr.next;            if (p != null) p = p.next;            if (q != null) q = q.next;        }        if(tag > 0){            curr.next = new ListNode(tag);        }        return newListNode.next;    }    //借用数组构造链表    public static void main(String[] args){        ListNode l1 = new ListNode(0),l2 = new ListNode(0);        ListNode current1 = l1,current2 = l2;        int[] array1 = {2,4,3};        int [] array2 = {5,6,4};        for (int i = 0; i < array1.length; i++) {            current1.next = new ListNode(array1[i]);            current1 = current1.next;        }        for (int i = 0; i < array2.length; i++) {            current2.next = new ListNode(array2[i]);            current2 = current2.next;        }        current1.next = null;        current2.next = null;        ListNode result = addTwoNumbers(l1.next,l2.next);        while (result !=null) {            System.out.print(result.value+" ");            result = result.next;        }    }}
原创粉丝点击