博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]AddTwoNumbers
阅读量:5015 次
发布时间:2019-06-12

本文共 2162 字,大约阅读时间需要 7 分钟。

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

代码:

// AddTwoNumbers.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include
using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *res,*p; int plus = 0,sum=0; res = new ListNode(0); p = res; while (l1 != NULL&&l2 != NULL) { sum = l1->val + l2->val+plus; //p = new ListNode(sum % 10); p->val = sum % 10; plus = sum / 10; l1 = l1->next; l2 = l2->next; if (l1 != NULL&&l2 != NULL) { ListNode *temp = new ListNode(0); p->next = temp; p = p->next; } } if (l1 == NULL&&l2 == NULL) { if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } else if (l1 == NULL) { while (l2 != NULL) { sum =l2->val + plus; ListNode *temp = new ListNode(sum % 10); plus = sum / 10; p->next = temp; p = p->next; l2 = l2->next; } if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } else if (l2 == NULL) { while (l1 != NULL) { sum = l1->val + plus; ListNode *temp = new ListNode(sum % 10); plus = sum / 10; p->next = temp; p = p->next; l1 = l1->next; } if (plus != 0) { ListNode *temp = new ListNode(plus); p->next = temp; p = p->next; } } return res; }};int _tmain(int argc, _TCHAR* argv[]){ ListNode *l1 = new ListNode(1); //ListNode *l2 = new ListNode(4); //ListNode *l3 = new ListNode(3); //l1->next = l2; //l2->next = l3; ListNode *ll1 = new ListNode(9); ListNode *ll2 = new ListNode(9); //ListNode *ll3 = new ListNode(4); ll1->next = ll2; //ll2->next = ll3; Solution ss; ListNode *res = ss.addTwoNumbers(l1,ll1); while (res != NULL) { cout << res->val << ""; res = res->next; } system("pause"); return 0;}

  

转载于:https://www.cnblogs.com/supernigel/p/4003743.html

你可能感兴趣的文章
作业2
查看>>
iOS 隐藏状态栏
查看>>
[SoapUI] Command-Line Arguments
查看>>
RIGHT JOIN 关键字
查看>>
adb与bat混用启动与杀死应用程序
查看>>
C基础 万能动态数组
查看>>
[HDU] 迷宫城堡 HDU - 1269
查看>>
通过response设置响应体
查看>>
如何计算合适的InnoDB log file size
查看>>
fdf
查看>>
在linux下安装dropbox
查看>>
socket编程的同步、异步与阻塞、非阻塞示例详解
查看>>
spring bean 生命周期
查看>>
Python中range的用法
查看>>
[Vue]axios 发出请求的config
查看>>
jQuery对象与DOM对象的相互转换
查看>>
如何将JPEG图片上的文字转换成word
查看>>
光线追踪算法—镜面反射
查看>>
如何将一个字符串中的所有非数字(0-9及小数点)字符全部除去
查看>>
关于JavaScript对象中的一切(二) -- 继承
查看>>