两个链表生成相加链表
描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。给定两个这种链表,请生成代表两个整数相加值的结果链表。例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
解题
单链表
public class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
Solution1
/**
* 链表存储的两数相加
* 1.反转链表后求解
*/
public class Solution {
public ListNode addInlist (ListNode head1,ListNode head2){
ListNode l1 = ReverseList(head1);//反转链表
ListNode l2 = ReverseList(head2);
int count= 0;//进位标志
ListNode result =null;
while (l1!=null||l2!=null){
int x1= l1!=null? l1.val:0;//空则为0
int x2= l2!=null? l2.val:0;
int sum=x1+x2+count;
count=sum/10;//进位
ListNode temp =new ListNode(sum%10);//取余存储
temp.next=result;
result=temp;
l1= l1==null? null:l1.next;
l2= l2==null? null:l2.next;
}
if (count>0){//处理结束后进位
ListNode temp =new ListNode(count);
temp.next=result;
result=temp;
}
return result;
}
private ListNode ReverseList(ListNode head) {
ListNode res= null;
ListNode cur= head;
while (cur!=null){
ListNode temp = cur.next;
cur.next=res;//拆分头部节点
res=cur;
cur=temp;
}
return res;
}
}
Solution2
/**
* 链表存储的两数相加
* 2.栈方法
*/
import java.util.Stack;
public class Solution2 {
public ListNode addInList(ListNode head1,ListNode head2){
Stack<Integer> s1 = new Stack<>();//创建存储数值的栈
Stack<Integer> s2 = new Stack<>();
while (head1!=null){
s1.push(head1.val);//压栈
head1=head1.next;
}
while (head2!=null){
s2.push(head2.val);
head2=head2.next;
}
int count = 0;
ListNode result = null;
while (!s1.isEmpty()||!s2.isEmpty()){
int x1= s1.isEmpty()? 0:s1.pop();//空则为0,不空则出栈
int x2= s2.isEmpty()? 0:s2.pop();
int sum=x1+x2+count;
count=sum/10;
ListNode temp = new ListNode(sum%10);//取余存储
temp.next=result;
result=temp;
}
if (count>0){//处理进位
ListNode temp = new ListNode(count);
temp.next=result;
result=temp;
}
return result;
}
}