zoukankan      html  css  js  c++  java
  • 链表求和

    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;
    }
    }
  • 相关阅读:
    PHP jquery结合HTML5鼠标拖选头像图片并上传
    HTML5 CSS3 SwitchButton 自定义Radio风格
    IE浏览器在虚拟机中无法正常显示字符
    jQuery在updatepanel中使用造成内存泄露
    bootstrap下拉列表重置联动
    bootstrap正则表达式验证手机 座机 邮箱
    bootstrap重置校验方法
    分页
    函数解一元二次方程
    集合
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10926822.html
Copyright © 2011-2022 走看看