描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
题解:利用堆栈这个特殊结构,对数据进行处理,使其可以从末尾开始相加,并用carry标志位存储进位标志。
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
LinkedList<Integer> set1=new LinkedList<>();
LinkedList<Integer> set2=new LinkedList<>();
while(head1!=null)
{
set1.push(head1.val);
head1=head1.next;
}
while(head2!=null)
{
set2.push(head2.val);
head2=head2.next;
}
ListNode head=new ListNode(0);
int carry=0;
int num1=0;
int num2=0;
while(!set1.isEmpty()||!set2.isEmpty())
{
if(!set1.isEmpty())
{
num1=set1.pop();
}
else{
num1=0;
}
if(!set2.isEmpty())
{
num2=set2.pop();
}
else{
num2=0;
}
num1=num1+num2+carry;
carry=num1/10;
ListNode node=new ListNode(num1%10);
node.next=head.next;
head.next=node;
}
if(carry==1) head.val=1;
return head.val==1?head:head.next;
}
}