002Add Two Numbers

来源:互联网 发布:2017成都软件行业 编辑:程序博客网 时间:2024/06/04 19:10

002Add Two Numbers

目录

  • 002Add Two Numbers
    • 目录
      • 题目内容
      • 我的代码
      • 小记

第二题比较简单,应该是最优的,只要处理好链表和地址即可,需要学习下函数中malloc和new关于内存的区别。

  • malloc与new

题目内容

==

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


我的代码:


/** * 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* tmp(0);        int i;        ListNode* first = (ListNode*)malloc(sizeof(ListNode));        tmp = first;        int remain=0;        while(l1!=NULL&&l2!=NULL)        {            ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));            temp_list->val = (remain + l1->val + l2->val)%10;            remain = (remain + l1->val + l2->val)/10;            tmp->next = temp_list;            tmp = temp_list;            l1 = l1->next;            l2 = l2->next;        }        while(l1!=NULL)        {            ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));            temp_list->val = (remain + l1->val)%10;            remain = (remain + l1->val)/10;            tmp->next = temp_list;            tmp = temp_list;            l1 = l1->next;        }        while(l2!=NULL)        {            ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));            temp_list->val = (remain + l2->val)%10;            remain = (remain + l2->val)/10;            tmp->next = temp_list;            tmp = temp_list;            l2 = l2->next;        }        if(remain!=0)        {            ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode));            temp_list->val = remain;            tmp->next = temp_list;            tmp = temp_list;        }        tmp->next = NULL;        return first->next;    }};

小记

认真即可,想清楚具体流程。

0 0
原创粉丝点击