445.两数相加II
题目描述
Leetcode:https://leetcode-cn.com/problems/add-two-numbers-ii/
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
解题思路
首先使用两个栈来存储两个链表中的数据,然后用头插法建立链表
java代码
/**
* 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> l1Stack = buildStack(l1);
Stack<Integer> l2Stack = buildStack(l2);
ListNode head = new ListNode(0);
int carry = 0;
while(!l1Stack.isEmpty() || !l2Stack.isEmpty() || carry != 0){
int x = l1Stack.isEmpty() ? 0 : l1Stack.pop();
int y = l2Stack.isEmpty() ? 0 : l2Stack.pop();
int sum = x + y + carry;
ListNode node = new ListNode(sum % 10);
node.next = head.next;
head.next = node;
carry = sum / 10;
}
return head.next;
}
private Stack<Integer> buildStack(ListNode l){
Stack<Integer> stack = new Stack<>();
while(l != null){
stack.push(l.val);
l = l.next;
}
return stack;
}
}
python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1 = self.buildStack(l1)
stack2 = self.buildStack(l2)
head = ListNode(0)
carry = 0
while stack1 or stack2 or carry != 0:
x = stack1.pop() if stack1 else 0
y = stack2.pop() if stack2 else 0
sum = x + y + carry
node = ListNode(sum % 10)
node.next = head.next
head.next = node
carry = sum // 10
return head.next
def buildStack(self, l: ListNode) -> List:
stack = []
while l != None:
stack.append(l.val)
l = l.next
return stack