445. Add Two Numbers II(JAVA)

来源:互联网 发布:淘宝账期延长十五天 编辑:程序博客网 时间:2024/06/11 04:24

原題

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

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


解題思路

先用棧儲存鏈表的數字,然後再把每位push出來計算其和,再推入另一個棧中。最後把結果存入鏈表中。


代碼

import java.util.*;


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> s1 = new Stack<Integer>(), s2 = new Stack<Integer>(), s3 = new Stack<Integer>();
        int count1 = 0, count2 = 0;


        while (l1 != null) {
            count1++;
            s1.push(l1.val);
            l1 = l1.next;
        }


        while (l2 != null) {
            count2++;
            s2.push(l2.val);
            l2 = l2.next;
        }
        
        if (count2 > count1) {
            count1 = count2;
        }
        
        
        boolean up = false;
        
        for (int i = 1; i <= count1; i++) {
            int num = 0;
            if (up == true) {
                num = 1;
                up = false;
            }
            
            if (!(s1.empty() || s2.empty())) {
                num += s1.pop() + s2.pop();
            }
            else if (s1.empty()) {
                num += s2.pop();
            }
            else {
                num += s1.pop();
            }
            
            if (num >= 10) {
                up = true;
                num -= 10;
            }
            
            s3.push(num);
        }
        
        if (up == true) {
            s3.push(1);
            count1++;
        }
        


        ListNode l3 = new ListNode(s3.pop()), l4;
        l4 = l3;
        for (int i = count1 - 2; i >= 0; i--) {
            l3.next = new ListNode(s3.pop());
            l3 = l3.next;
        }
        
        return l4;
    }
}



感想

這次我用了java來寫,因為這幾天一直在寫java,都有點忘了c++怎麼寫了。。。

這題挺簡單的,只要從最後一位開始往前算的好了,還有就是要注意進位,沒有甚麼難點。

原创粉丝点击