博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode: Add Two Numbers
阅读量:4608 次
发布时间:2019-06-09

本文共 1263 字,大约阅读时间需要 4 分钟。

You are given two linked lists representing two non-negative numbers. 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.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8

思路

注意以下两点,其它都简单:

  1. 两个链表长度不一样。
  2. 进位的处理。
1 class Solution { 2 public: 3     void insertNode(ListNode *node, ListNode *&head, ListNode *&tail) { 4         if (NULL == head) { 5             head = tail = node; 6         } 7         else { 8             tail->next = node; 9             tail = node;10         }11     }12 13     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {14         ListNode *head = NULL, *tail = NULL;15         int sum, flag = 0;16 17         while ((l1 != NULL) || (l2 != NULL)) {18             sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + flag;19             flag = sum / 10;20             insertNode(new ListNode(sum % 10), head, tail);21 22             l1 = (l1 != NULL) ? l1->next : NULL;23             l2 = (l2 != NULL) ? l2->next : NULL;24         }25 26         if (flag > 0) {27             insertNode(new ListNode(flag), head, tail);28         }29 30         return head;31     }32 };

 

转载于:https://www.cnblogs.com/panda_lin/p/add_two_numbers.html

你可能感兴趣的文章
React之特点及常见用法
查看>>
【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
查看>>
优云软件助阵GOPS·2017全球运维大会北京站
查看>>
linux 装mysql的方法和步骤
查看>>
poj3667(线段树区间合并&区间查询)
查看>>
51nod1241(连续上升子序列)
查看>>
SqlSerch 查找不到数据
查看>>
集合相关概念
查看>>
Memcache 统计分析!
查看>>
(Python第四天)字符串
查看>>
个人介绍
查看>>
使用python动态特性时,让pycharm自动补全
查看>>
MySQL数据库免安装版配置
查看>>
你必知必会的SQL面试题
查看>>
html5 Canvas绘制时钟以及绘制运动的圆
查看>>
Unity3D热更新之LuaFramework篇[05]--Lua脚本调用c#以及如何在Lua中使用Dotween
查看>>
JavaScript空判断
查看>>
洛谷 P1439 【模板】最长公共子序列(DP,LIS?)
查看>>
python timeit
查看>>
Wireless Network 并查集
查看>>