public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
//push all value into stack
while(l1!=null){
s1.push(l1.val);
l1=l1.next;
}
while(l2!=null){
s2.push(l2.val);
l2=l2.next;
}
//get the value out one by one while doing add
int sum=0;
ListNode cur = new ListNode(0);
while(!s1.empty()||!s2.empty()){
if(!s1.empty()) sum+=s1.pop();
if(!s2.empty()) sum+=s2.pop();
cur.val = sum%10;
ListNode head = new ListNode(sum/10);//括号里是val 参看ListNode的定义
head.next = cur;
cur = head;//this means that the first getin is the last node in the list
sum/=10;
}
return cur.val==0?cur.next:cur;//judge whether the cur.val ==0 or not. if == 0, then the first node need to be the cur.next. if not, the first node is cur
}
}
补充题目:
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.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
LinkedList 还有一些常用的函数:
size(): return the number of element in the list
add(e): add element
这里 list就是代码里的cur
每次循环,上一次循环虽然list被赋值了,但是新的循环会update它的值