010-两个单链表生成相加链表

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;
		}
		//n1记录s1每次弹出的数
		int n1 = 0;
		//n2记录s2每次弹出的数
		int n2 = 0;
		//n两数相加的结果
		int n = 0;
		//ca记录每次弹出的两个数的和的进位
		int ca = 0;
		//pre记录上个新节点的值
		SingleNode pre = null;
		//cur记录此刻新节点的值
		cur = null;
		while(!s1.isEmpty() || !s2.isEmpty()) {
			//判断栈是否为空,如果为空,则当前值为0
			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;
		}
		//当两个栈都为空时,如果还有进位,(因为每个数都在0-9,所以如果有进位,则该进位一定为1),则要生成一个新的节点来保存最高位
		if(ca == 1) {
			pre = cur;
			cur = new SingleNode(1);
			cur.next = pre;
		}
		//此时cur保存的是新的链表的头结点,返回新链表的头结点
		return cur; 
	}
	
	/**
	 * 方法二:利用链表的逆序求解,可以省掉栈结构的额外空间
	 * */
	public SingleNode addLists2(SingleNode head1, SingleNode head2) {
		//反转两个链表
		head1 = reverseList(head1);
		head2 = reverseList(head2);
		//n1记录s1每次弹出的数
		int n1 = 0;
		//n2记录s2每次弹出的数
		int n2 = 0;
		//n两数相加的结果
		int n = 0;
		//ca记录每次弹出的两个数的和的进位
		int ca = 0;
		//记录当前节点
		SingleNode cur = null;
		//记录上一个节点
		SingleNode pre = null;
		//记录第一个链表的头结点
		SingleNode c1 = head1;
		//记录第二个链表的头结点
		SingleNode c2 = head2;
		while(c1 != null || c2 != null) {
			//给n1赋值
			n1 = c1 == null ? 0 : c1.value;
			//给n2赋值
			n2 = c1 == null ? 0 : c2.value;
			n = n1 + n2 + ca;
			//先用pre记录上一个节点
			pre = cur;
			cur = new SingleNode(n % 10);
			cur.next = pre;
			ca = n / 10;
			//c1,c2向后移动一个节点
			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) {
		//pre记录正在遍历的节点的上一个节点
		SingleNode pre = null;
		//next记录正在遍历的节点的下一个节点
		SingleNode next = null;
		while(head != null) {
			next = head.next;
			head.next = pre;
			pre = head;
			head = next;
		}
		//此时head为空,pre记录的是原链表的尾节点,也就是翻转后的链表的头结点
		return pre;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值