两个链表相加(Leetcode445)

2018-11-13  本文已影响0人  zhouwaiqiang

题目

解题思路

源代码实现

/**
 * 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<ListNode> stack1 = new Stack<>();
        Stack<ListNode> stack2 = new Stack<>();
        ListNode index1 = l1, index2 = l2;
        int length1=0, length2=0;
        int carry = 0;//进位符
        while (index1 != null || index2 != null) {
            if (index1 != null) {
                stack1.push(index1);
                index1 = index1.next;
                length1++;
            }
            if (index2 != null) {
                stack2.push(index2);
                index2 = index2.next;
                length2++;
            }
        }
        if (length1 > length2) {
            while (!stack1.isEmpty()) {
                ListNode temp1 = stack1.pop();
                int val2 = stack2.isEmpty() ? 0 : stack2.pop().val;
                int result = temp1.val + val2 + carry;
                temp1.val = result % 10;
                carry = result / 10;
            }
            if (carry == 1) {
                ListNode newNode = new ListNode(1);
                newNode.next = l1;
                return newNode;
            } else return l1;
        } else {
            while (!stack2.isEmpty()) {
                int val1 = stack1.isEmpty() ? 0 : stack1.pop().val;
                ListNode temp2 = stack2.pop();
                int result = val1 + temp2.val + carry;
                temp2.val = result % 10;
                carry = result / 10;
            }
            if (carry == 1) {
                ListNode newNode = new ListNode(1);
                newNode.next = l2;
                return newNode;
            } else return l2;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读