leetcode:Add Two Numbers

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

题目意思就是给定两个链表,每一个链表中的数都是倒序查入的,需要将其取出按插入之前的顺序相加并将每位再按倒序插入新的链表。

第一种思路很简单:分别取出每个链表中的数字再合并组成一个整数,再将两个整数相加后将每位倒序存入新链表;

第二种思路:因为刚好是倒序插入的,所以可以将两个链表对应从头开始相加,将相加后的个位直接存入新链表,

如果有进位则进位保存继续与两个链表的下一节点继续相加

下面是我的代码,格式有点乱

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    typedef struct ListNode list, *listnode;
    listnode pt, p1, p2, head, last;
    int a, b = 0;					//b保存进位信息,如果有进位则为1,否则为0
    head = (listnode)malloc(sizeof(struct ListNode));	
    head->next = NULL;
    last = head;
    pt = head;
    p1 = l1;
    p2 = l2;
    while(p1 || p2)
    {
        if(p1 && p2)
        {
            a = p1->val + p2->val + b;
            b = a/10;
            pt = (listnode)malloc(sizeof(struct ListNode));
            pt->val = (a/10)>0?(a%10):a;
            pt->next = NULL;
            last->next = pt;
            last = pt;
            p1 = p1->next;
            p2 = p2->next;
        }
        else if(p1 && p2==NULL)
        {
            a = p1->val + b;
            b = a/10;
            pt = (listnode)malloc(sizeof(struct ListNode));
            pt->val = (a/10)>0?(a%10):a;
            pt->next = NULL;
            last->next = pt;
            last = pt;
            p1 = p1->next;
        }
        else
        {
            a = p2->val + b;
            b = a/10;
            pt = (listnode)malloc(sizeof(struct ListNode));
            pt->val = (a/10)>0?(a%10):a;
            pt->next = NULL;
            last->next = pt;
            last = pt;
            p2 = p2->next;
        }
    }
    if(b>0)
    {
        pt = (listnode)malloc(sizeof(struct ListNode));
        pt->val = b;
        pt->next = NULL;
        last->next = pt;
    }
    last = head;
    head = head->next;
    free(last);				//因为头结点未保存数据,所以要free掉,并将头结点后移一位
    return head;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值