题目
分析
加法是从后往前运算,但是链表的结构是从前往后,因此要实现加法要反转链表,我们可以借助一个栈结构,具体实现如下:
代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
Stack<ListNode> s1 = new Stack();
Stack<ListNode> s2 = new Stack();
ListNode p1 = head1;
ListNode p2 = head2;
while(p1 != null) {
s1.push(p1);
p1 = p1.next;
}
while(p2 != null) {
s2.push(p2);
p2 = p2.next;
}
//定义一个头结点
ListNode head = new ListNode(-1);
int carry = 0;
while(!s1.isEmpty() || !s2.isEmpty()) {
int val1 = s1.isEmpty()?0:s1.pop().val;
int val2 = s2.isEmpty()?0:s2.pop().val;
int result = val1 + val2 + carry;
ListNode node = new ListNode(result % 10);
node.next = head.next;
head.next = node;
carry = result / 10;
}
if(carry != 0) {
ListNode node = new ListNode(carry);
node.next = head.next;
head.next = node;
}
return head.next;
}
}
时间复杂度:o(max(m,n)),m和n是两个链表的长度。