List_NC40

两个链表生成相加链表

描述

假设链表中每一个节点的值都在 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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值