【Leetcode】【Medium】Add Two Numbers
2024-10-18 19:24:02
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、链表已经是倒序的,因此首结点就是个位数字;
解题步骤:
1、建立preHead结点,指向新链表表头,新链表记录加法结果;(注意新建链表,不要在原链表上操作)
2、新建整形flag,记录进位;
3、开始循环操作,只要L1和L2有一个不为空,循环继续:
(1)新建临时整形sum,初始值为flag;
(2)L1不为空,则加上L1的值;L2不为空,则加上L2的值;
(3)flag = sum / 10; sum = sum % 10;
(4)记录在新建链表上;
4、如果flag还存在值,则再新建一个结点;
5、记录preHead->next地址head,delete preHead,返回head;
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode* preheader = new ListNode();
ListNode* newlist = preheader;
int flag = ; while (l1 || l2) {
int sum = flag;
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
} flag = sum / ;
sum = sum % ;
newlist->next = new ListNode(sum);
newlist = newlist->next;
} if (flag)
newlist->next = new ListNode(flag); return preheader->next;
}
};
最新文章
- git学习之冲突解决办法
- Spring为某个属性注入值或为某个方法的返回值
- PHP获取远程图片并调整图像大小(转)
- hdu 2177 取(2堆)石子游戏 博弈论
- 使用Java VisualVM监控远程JVM
- HDU-4737 A Bit Fun 维护
- Java多线程初学者指南(5):join方法的使用
- Duplex Service in WCF(CodeProject上的)
- 让Barebox正确引导Tiny6410的linux内核
- poj2409 Let it Bead
- C# 堆栈和堆 Heap &; Stack
- Codeforces 1092C Prefixes and Suffixes(思维)
- JQ01
- [20180718]拷贝数据文件从dg库.txt
- MySQl中的\g和\G
- 【原】MySQL实用SQL积累
- sql2008 安装提示重启失败
- 从12306网站新验证码看Web验证码设计与破解
- 基于FPGA的HDMI显示设计(三)
- Install nginx on ubuntu