LeetCode 2. Add Two Numbers(单链表求和)

本文介绍了一种算法,用于解决两个非空、非负整数元素的单链表相加问题。通过尾插法构建结果链表,实现了高效的链表加法。

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

题目描述:

    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
Explanation: 342 + 465 = 807.


分析:

   题意:给定两个非空、非负整数元素的单链表,它们可以看作两个整数的逆序排列形式。求两个整数和的逆序排列单链表。假设不存在前置零的问题。
  思路:考察整数加法单链表插入法。我们用指针p,q分别指向两个单链表头部顺序遍历,用指针r开辟新的单链表结点空间保存和。每次相加结果模10作为数值,除以10作为进制,r指针采用尾插法保存结果(头插法会形成逆序、尾插法会保持正序),最后返回r指针作为结果。假设两个单链表结点数为m、n,时间复杂度为O(max(m, n))。


代码:

#include <bits/stdc++.h>

using namespace std;

// Definition for singly-linked list
struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x): val(x), next(NULL){}
};

class Solution {
private: 
	// Tail insertion method: keep the nodes' order
	void add(ListNode *&r, int digit){
		r->next = new ListNode(digit);
		r = r->next;			
	}

public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        // Exceptional Case: 
		if(!l1){
			return l2;
		}
		if(!l2){
			return l1;
		}
		// Add an extra empty ListNode(-1) is convenient for the operation of pointer r
		ListNode *p = l1, *q = l2, *l3 = new ListNode(-1), *r = l3;
		int digit = 0, carry = 0;
		while(p && q){
			digit = (p->val + q->val + carry) % 10;
			carry = (p->val + q->val + carry) / 10;
			add(r, digit);
			p = p->next;
			q = q->next;
		}
		while(p){
			digit = (p->val + carry) % 10;
			carry = (p->val + carry) / 10;
			add(r, digit);
			p = p->next;
		}
		while(q){
			digit = (q->val + carry) % 10;
			carry = (q->val + carry) / 10;
			add(r, digit);
			q = q->next;
		}
		if(carry){
			add(r, 1);
		}
		return l3->next;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值