题目:
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1:
输入:l1 = [7,2,4,3], l2 = [5,6,4] 输出:[7,8,0,7]
示例2:
输入:l1 = [2,4,3], l2 = [5,6,4] 输出:[8,0,7]
示例3:
输入:l1 = [0], l2 = [0] 输出:[0]
答案:
用的反转链表1ms(注释的部分用栈5ms)
**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry=0; //表示进位
ListNode pre1=null; //迭代反转链表的头
ListNode pre2=null;
ListNode next1; //原链表l1结点的next
ListNode next2;
while(l1!=null){
next1=l1.next;
l1.next=pre1;
pre1=l1;
l1=next1;
}
while(l2!=null){
next2=l2.next;
l2.next=pre2;
pre2=l2;
l2=next2;
}
ListNode head=null; //相加后新链表的的head
while(pre1!=null||pre2!=null||carry!=0){
int sum=carry;
sum+=pre1==null?0:pre1.val;
sum+=pre2==null?0:pre2.val;
carry=sum/10;
pre1=pre1==null?pre1:pre1.next;
pre2=pre2==null?pre2:pre2.next;
ListNode node=new ListNode(sum%10);
node.next=head;
head=node;
}
// Stack<Integer>stack1=new Stack<>();
// Stack<Integer>stack2=new Stack<>();
// Stack<Integer>stack=new Stack<>();
// ListNode l=new ListNode();
// ListNode cur=l;
// ListNode head=null; //相加后新链表的的head
// while(l1!=null||l2!=null){
// if(l1!=null){
// stack1.push(l1.val);
// l1=l1.next;
// }
// if(l2!=null){
// stack2.push(l2.val);
// l2=l2.next;
// }
// }
// while(stack1.size()!=0||stack2.size()!=0||carry!=0){
// int sum=carry;
// sum+=stack1.isEmpty()?0:stack1.pop();
// sum+=stack2.isEmpty()?0:stack2.pop();
// carry=sum/10;
// ListNode node=new ListNode(sum%10);
// node.next=head;
// head=node;
// }
return head;
}
}