LeetCode #002 Add Two Numbers

本文深入解析了LeetCode上的一道中等难度的链表加法问题,详细讲解了如何通过简单的链表操作解决该问题,并提供了实现代码。重点强调了解题时需要注意的关键点,如链表长度不一致、进位处理等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题地址:https://leetcode.com/problems/add-two-numbers/

2. Add Two Numbers

My Submissions
Total Accepted: 133372  Total Submissions: 587079  Difficulty: Medium

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss

这题不难,使用简单的链表即可完成,不知道为什么LeetCode把它放在中等难度,不过如果不好好理解题意的话还是会有诸多问题的,下面讲下注意点:


1. 每个节点数值相加取个位数,把进位加到下一位。


2. 链表1和链表2不一定一样长,如果不一样长,在计算最后一个节点的时候,把短表中的节点值看作0。


3. 如果存在进位,进位要作为一个必须加入节点的值,简单说,链表1和链表2长度为3,在[2]位置相加存在进位,则,输出的链表的最后一位[3]为1,链表长度为4。


总的来说编程没什么难度,但要读懂题目,注意以上的注意点,下面放出我的实现代码:


class Solution {
public:
	ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

		ListNode* results=new ListNode(0);
		ListNode* p = results;
		int rise = 0;
		
		while(true){
			bool flag = false;
			int num = l1->val + l2->val+rise;
			p->val = num % 10;
			if ((num / 10) > 0) {
				rise = num / 10;
				flag = true;
			}
			else {
				rise = 0;
				flag = false;
			}
			l1->val = 0;
			l2->val = 0;
			if (l1->next != NULL) {
				l1 = l1->next;
				flag = true;
			}
			if (l2->next != NULL) {
				l2 = l2->next;
				flag = true;
			}
			if (flag)p->next = new ListNode(0);
			if (p->next == NULL)break;
			p = p->next;
		}
		
		return results;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值