【数据结构与算法】链表——两数相加Ⅰ&Ⅱ

两数相加

LeetCode:两数相加

题目描述:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

思想:

链表遍历,关键的地方在于补0,因为两个链表长短可能不一致,不补0的话很麻烦

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1,q=l2;
        int twoSum=0,nextAdd=0;
        while(p!=null||q!=null){ 
            if(p.next==null&&q.next!=null)
                p.next = new ListNode(0);
            if(q.next==null&&p.next!=null)
                q.next = new ListNode(0);
            twoSum = p.val + q.val;
            p.val = (twoSum + nextAdd)%10;
            nextAdd = (twoSum + nextAdd)/10;
            if(p.next==null&&q.next==null&&nextAdd>0){
                p.next = new ListNode(nextAdd);
                break;
            }
            p=p.next;
            q=q.next;
        }
        return l1;
    }
}

两数相加 II

LeetCode:两数相加 II

题目描述:

给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

思想:

与上一题不一样,链表顺序是反过来的,使用栈进行处理。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stackL1 = buildStack(l1);
        Stack<Integer> stackL2 = buildStack(l2);
        ListNode L=null,p=null;
        int x,y,item,carry=0;
        while(!(stackL1.empty()&&stackL2.empty()) || carry>0){
            x = stackL1.empty()?0:stackL1.pop();
            y = stackL2.empty()?0:stackL2.pop();
            item = (x+y+carry)%10;
            carry = (x + y + carry)/10;
            L = new ListNode(item);
            L.next = p;
            p = L;
        }
        return L;
    }
    private Stack<Integer> buildStack(ListNode L){
        Stack<Integer> stack = new Stack<>();
        while(L!=null){
            stack.push(L.val);
            L=L.next;
        }
        return stack;
    }
}
原文地址:https://www.cnblogs.com/buptleida/p/12672249.html