链表问题10——两个单链表生成相加链表

题目

假设链表中每一个节点的值都在0-9之间,链表整体代表一个整数。

给定两个这种链表的头节点,请生成代表两个整数相加值的结果链表。

链表1 链表2 生成的新链表
9->3->7 6->3 1->0->0->0

思路 

有一种实现方式是先分别算出两个链表所代表的整数,然后求出两个整数的和,最后将这个和转换成链表的形式。但是这种方法有一个很大的问题,链表的长度可以很长,表达一个很大的整数。因此转换成int类型时可能溢出,所有不推荐此方法。

方法一:利用栈结构求解

  1. 分别遍历两个链表,并压栈,这样就生成了两个链表值的逆序栈,分别记为s1和s2
  2. 将s1和s2同步弹出,并检查是否有进位,用ca表示,在这个过程中生成相加链表即可。
  3. 当s1和s2都为空时,还要关注进位信息是否为1,如果为1,还需要生成一个节点值为1的新节点。
  4.        返回新生产的结果链表即可。

源码

public class Node{
	public int value;
	public Node next;
	public Node(int data){
		this.value=data;
	} 
}

public Node addList1(Node head1,Node head2){
	Stack<Integer> s1=new Stack<Integer>();
	Stack<Integer> s1=new Stack<Integer>();
	while(head1!=null){
		s1.push(head1.value);
		head1=head1.next;
	}
	while(head2!=null){
		s2.push(head2.value);
		head2=head2.next;
	}
	//进位
	int ca=0;
	int n1=0;
	int n2=0;
	int n=0;
	Node node=null;
	Node pre=null;
	while(!s1.isEmpty()||!s2.isEmpty()){
		n1=s1.isEmpty()?0:s1.pop();
		n2=s2.isEmpty()?0:s2.pop();
		pre=node;
		n=n1+n2+ca;
		node=new Node(n%10);
		node.next=pre;
		ca=n/10;
	}
	if(ca==1){
		pre=node;
		node=new Node(1);
		node.next=pre;
	}
	return node;
}
发布了43 篇原创文章 · 获赞 21 · 访问量 4907

猜你喜欢

转载自blog.csdn.net/flying_1314/article/details/103902319
今日推荐