借助链表实现两个数的相加

链式列表的数字高位在前与低位在前

这篇博客主要讲了借助链表实现两个数字的相加。链表分别是高位数字在前和低位数字在前

  • 高位在前
  • 低位在前

高位在前

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

对于这个题目,我实现的时候记住了栈,首先便利这两个链表,将数字放入栈里,由于高位在前,所以使用栈的话,低位就在栈顶了,然后遍历栈,结果放入一个栈,这样就又将高位放到了栈顶,这时候将数字从栈里弹出建立链表,就实现了;这种做法虽然时间复杂度是O(n),但是空间复杂度也是O(n);比较好的方法应该是将链表反向,然后直接相加,但是我这样做的时候出现了一些状况,还没有将程序弄对,等以后做出来了再贴上代码吧。
下面贴上这道题的代码:

/**
 * 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) {
        struct ListNode* ne = new struct ListNode(0);
        int carry = 0<
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值