给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?
示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
分析:
反向方法:模拟
因为是从个位开始,所以只需要记录是否进位,两个节点相加取10的余数,然后遍历下两个节点,求和时加上进位的数,然后重复操作,直到两条链表都遍历完。
时间复杂度:O(n) n 为最长链表长度
空间复杂度:O(n)
/**
* 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) {
//记录进位
int carry = 0;
//结果节点
ListNode node = new ListNode(0), res = node;
//遍历
while(true){
//都为空
if(l1 == null && l2 == null){
//进位
if(carry == 1){
node.next = new ListNode(1);
}
return res.next;
}
//获取两个的值
int a = 0, b = 0;
//l1不为空
if(l1 != null){
a = l1.val;
l1 = l1.next;
}
//l2不为空
if(l2 != null){
b = l2.val;
l2 = l2.next;
}
//求和
int sum = a + b + carry;
//进位
carry = sum / 10;
//求和创建新节点
node.next = new ListNode(sum % 10);
node = node.next;
}
}
}
正向方法: 栈
先遍历一遍,分别将两个链表的值存入两个栈中,然后再遍历栈同反向方法一样遍历。
时间复杂度:O(m+n) m、n 分别为两个链表长度
空间复杂度:O(m+n)
/**
* 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) {
//创建栈
Deque<Integer> s1 = new ArrayDeque<>();
Deque<Integer> s2 = new ArrayDeque<>();
//遍历存储
while(l1 != null){
s1.addLast(l1.val);
l1 = l1.next;
}
while(l2 != null){
s2.addLast(l2.val);
l2 = l2.next;
}
//记录进位
int carry = 0;
//创建结果节点
ListNode node = new ListNode(0), res = node;
//遍历栈
while(true){
//栈都为空
if(s1.isEmpty() && s2.isEmpty()){
//进位
if(carry == 1){
node.next = new ListNode(1);
}
return res.next;
}
//获取两个的值
int a = 0, b = 0;
//s1不为空
if(!s1.isEmpty()){
a = s1.pollLast();
}
//s2不为空
if(!s2.isEmpty()){
b = s2.pollLast();
}
//求和
int sum = a + b + carry;
//进位
carry = sum / 10;
//求和创建新节点
ListNode temp = new ListNode(sum % 10);
temp.next = node.next;
node.next = temp;
}
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-lists-lcci