• 链表求和


    leetCode:

    https://leetcode.com/problems/add-two-numbers-ii/description/

    描述:

    You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Follow up:
    What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

    Example:

    Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 8 -> 0 -> 7


    这题最容易想到的思路就是将链表反转,然后同时遍历两个链表,最后再将加和后的链表反转回来。
    但是题目最后提高了难度,如果原链表不能改变,也就是不能反转链表,该如何解决呢??

    答案就是使用栈,遍历链表依次将元素压入栈中,元素的顺序就被反转过来了,低位的数字在栈上面,高位的数字在栈底部。
    循环第从两个栈顶弹出元素,执行加法逻辑,并将相加后的元素放入一个新的栈中,这样求和结果中低位数字在栈底,高位数字在栈顶,

    最后循环从栈顶弹出元素,构建节点之间的指向关系,形成从高位到低位的链表。

    代码:

    public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    Stack<Integer> stack1 = pushToStck(l1);
    Stack<Integer> stack2 = pushToStck(l2);
    Stack<ListNode> result = new Stack<>();
    int carry = 0;
    while (true) {
    if (stack1.isEmpty() && stack2.isEmpty()) {
    break;
    }
    int s1 = stack1.isEmpty() ? 0 : stack1.pop();
    int s2 = stack2.isEmpty() ? 0 : stack2.pop();
    result.push(new ListNode((s1 + s2 + carry) % 10));
    carry = (s1 + s2 + carry) / 10;
    }
    if (carry != 0) {
    result.push(new ListNode(1));
    }
    ListNode newHead = null, newTail = null;
    while (!result.isEmpty()) {
    if (newHead == null) {
    newHead = newTail = result.pop();
    } else {
    newTail.next = result.pop();
    newTail = newTail.next;
    }
    }
    return newHead;
    }

    public Stack<Integer> pushToStck(ListNode l) {
    Stack<Integer> stack = new Stack<>();
    while (l != null) {
    stack.push(Integer.valueOf(l.val));
    l=l.next;
    }
    return stack;
    }
    }
  • 相关阅读:
    在Perl里 对象就是hash引用
    第十二章 对象(上):
    连锁百货企业数据分析系统建设方案
    连锁百货企业数据分析系统建设方案
    java.lang.ClassNotFoundException: com.fasterxml.jackson.core.JsonProcessingException
    通过Net::Ping 理解Perl的面向对象
    org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
    Attempt to refer to a unregistered pool by its alias 'dbpool'
    Error:[$parse:lexerr]
    keepalived 监测域名解析脚本
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10926822.html
Copyright © 2020-2023  润新知