题目描述:
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
弄了好长时间啊,
代码:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode listNode1 = reverse(l1);
ListNode listNode2 = reverse(l2);
ListNode list1 = new ListNode(0);
ListNode list2 = new ListNode(0);
list1.next = listNode1;
list2.next = listNode2;
int jinwei = 0;
while (list1.next != null && list2.next != null) {
int tem = list1.next.val + list2.next.val + jinwei;
list1.next.val = tem % 10;
jinwei = tem / 10;
list1 = list1.next;
list2 = list2.next;
}
if(list1.next == null){
list1.next = list2.next;
}
int tem = 0;
while (list1.next != null) {
tem = list1.next.val + jinwei;
list1.next.val = tem % 10;
jinwei = tem / 10;
list1 = list1.next;
}
if(jinwei == 1){
ListNode listNode = new ListNode(jinwei);
list1.next = listNode;
listNode.next = null;
}
return reverse(listNode1);
}
public ListNode reverse(ListNode head){
ListNode pre = null;
while (head != null) {
ListNode tem = head;
head = head.next;
tem.next = pre;
pre = tem;
}
return pre;
}
}
当然可以这么来,这样就不用翻转了
使用两个栈来存储
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1=new Stack();
Stack<Integer> stack2=new Stack();
ListNode node1=l1;
while(node1!=null){
stack1.push(node1.val);
node1=node1.next;
}
ListNode node2=l2;
while(node2!=null){
stack2.push(node2.val);
node2=node2.next;
}
ListNode head=null;
int flag=0;
while(!stack1.isEmpty()||!stack2.isEmpty()||flag!=0){
int value=0;
if(!stack1.isEmpty())
value+=stack1.pop();
if(!stack2.isEmpty())
value+=stack2.pop();
value+=flag;
ListNode node=new ListNode(value%10);
flag=value/10;
node.next=head;
head=node;
}
return head;
}
}
但是速度不如第一种方法;