package com.my.util;
public class SingleNode {
public int value;
public SingleNode next;
public SingleNode(int data){
this.value = data;
}
}
package com.my.suanfa;
import java.util.Stack;
import com.my.util.SingleNode;
public class Solution07 {
public SingleNode addLists1(SingleNode head1, SingleNode head2) {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
SingleNode cur = head1;
while(cur != null) {
s1.push(cur.value);
cur = cur.next;
}
cur = head2;
while(cur != null) {
s2.push(cur.value);
cur = cur.next;
}
int n1 = 0;
int n2 = 0;
int n = 0;
int ca = 0;
SingleNode pre = null;
cur = null;
while(!s1.isEmpty() || !s2.isEmpty()) {
n1 = s1.isEmpty() ? 0 : s1.pop();
n2 = s2.isEmpty() ? 0 : s2.pop();
n = n1 + n2 + ca;
pre = cur;
cur = new SingleNode(n % 10);
cur.next = pre;
ca = n / 10;
}
if(ca == 1) {
pre = cur;
cur = new SingleNode(1);
cur.next = pre;
}
return cur;
}
public SingleNode addLists2(SingleNode head1, SingleNode head2) {
head1 = reverseList(head1);
head2 = reverseList(head2);
int n1 = 0;
int n2 = 0;
int n = 0;
int ca = 0;
SingleNode cur = null;
SingleNode pre = null;
SingleNode c1 = head1;
SingleNode c2 = head2;
while(c1 != null || c2 != null) {
n1 = c1 == null ? 0 : c1.value;
n2 = c1 == null ? 0 : c2.value;
n = n1 + n2 + ca;
pre = cur;
cur = new SingleNode(n % 10);
cur.next = pre;
ca = n / 10;
c1 = c1 == null ? null : c1.next;
c2 = c2 == null ? null : c2.next;
}
if(ca == 1) {
pre = cur;
cur = new SingleNode(1);
cur.next = pre;
}
reverseList(head1);
reverseList(head2);
return cur;
}
public SingleNode reverseList(SingleNode head) {
SingleNode pre = null;
SingleNode next = null;
while(head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}