题目
假设链表中每一个节点的值都在0-9之间,链表整体代表一个整数。
给定两个这种链表的头节点,请生成代表两个整数相加值的结果链表。
链表1 | 链表2 | 生成的新链表 |
9->3->7 | 6->3 | 1->0->0->0 |
思路
有一种实现方式是先分别算出两个链表所代表的整数,然后求出两个整数的和,最后将这个和转换成链表的形式。但是这种方法有一个很大的问题,链表的长度可以很长,表达一个很大的整数。因此转换成int类型时可能溢出,所有不推荐此方法。
方法一可以参考我的前一篇文章。
方法二:利用栈的逆序求解,可以节省用栈的空间。
- 分别将两个链表逆序。
- 同步遍历逆序后的两个链表,在这个过程中生成相加链表即可,同时需要关注每一步是否有进位,用ca表示。
- 当两个链表遍历完后,还要关注进位信息是否为1,如果为1,还要生成一个节点值为1的新节点。
- 将两个逆序链表再逆序一次,即调整为原来的样子
- 返回新生成的结果链表。
源码
public class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public Node addList2(Node head1,Node head2){
head1=reverseList(head1);
head2=reverseList(head2);
//进位
int ca=0;
int n1=0;
int n2=0;
int n=0;
Node c1=head1;
Node c2=head2
Node node=null;
Node pre=null;
while(c1!=null||c2!=null){
n1=c1==null?0:c1.value;
n2=c2==null?0:c2.value;
pre=node;
n=n1+n2+ca;
node=new Node(n%10);
node.next=pre;
c1=c1!=null?c1.next:null;
c2=c2!=null?c2.next:null;
ca=n/10;
}
if(ca==1){
pre=node;
node=new Node(1);
node.next=pre;
}
reverseList(head1);
reverseList(head2);
return node;
}
public Node reverseList(Node head){
Node pre=null;
Node cur=head;
Node next=head;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}