zoukankan      html  css  js  c++  java
  • 面试题:Add Two Numbers(模拟单链表)

    题干:

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.

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

    注:

    题目中链表的定义为

    1 public class ListNode {
    2     int val;
    3     ListNode next;
    4 
    5     ListNode(int val) {
    6         this.val = val;
    7     }
    8 }

    分析:

      题干中链表中的数是倒序存储的,题干中给的例子其实是:342+465=807。

      我们定义一个节点dummyHead来指向结果的头结点,然后定义三个节点p,q,curr分别用来记录l1当前节点,l2当前节点,结果当前节点。

      定义int carry来记录是否有进位。

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummyHead = new ListNode(0);
            ListNode p = l1, q = l2, curr = dummyHead;
            int carry = 0;
            while (p != null || q != null) {
                int x = (p != null) ? p.val : 0;
                int y = (q != null) ? q.val : 0;
                int sum = carry + x + y;
                carry = sum / 10;
                curr.next = new ListNode(sum % 10);
                curr = curr.next;
                if (p != null)
                    p = p.next;
                if (q != null)
                    q = q.next;
            }
            if (carry > 0) {
                curr.next = new ListNode(carry);
            }
            return dummyHead.next;
        }
  • 相关阅读:
    技术晨读_2015_11_29
    mysql的timeout
    Gradle目录解析
    flexbox简介
    elasticsearch 查询(match和term)
    内存那些事
    elasticsearch 文档
    elasticsearch 集群
    elasticsearch中的API
    小菜的程序员道路(三)
  • 原文地址:https://www.cnblogs.com/kkkky/p/7768063.html
Copyright © 2011-2022 走看看