LeetCode --- Add Two Numbers
2015-05-29 07:37
435 查看
Add Two Numbers
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
My Submitted Code
/** * 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* head=NULL; ListNode* tail=NULL; ListNode* p1=l1; ListNode* p2=l2; list<int> carrs; while(p1||p2){ int carry=0; if (!carrs.empty()) { carrs.pop_back(); carry=1; } int sum=0; if(p1){ sum+=p1->val; } if(p2){ sum+=p2->val; } sum+=carry; if(sum>=10){ carrs.push_back(1); } ListNode* node=new ListNode(sum%10); if(!head){ head=node; tail=node; }else{ tail->next=node; tail=node; } if(p1){ p1=p1->next; } if(p2){ p2=p2->next; } } if(!carrs.empty()){ ListNode* node=new ListNode(1); tail->next=node; } return head; } };
相关文章推荐
- Java 集合类详解
- PostgreSQL 中文文档
- 大顶堆排序C实现--【严蔚敏数据结构实现】
- greedy algorithm demo(knapsack problem)
- jQuery Ajax 调用后台方法
- C++基础学习—vector
- 多版本并发控制
- POJ 3320 Jessica's Reading Problem
- redis高可用之redis3.0集群
- 第一次登台讲课的经历——北漂18年(11)
- 119 Pascal's Triangle
- Floyd Warshall 弗洛伊德算法---最短路径
- ScrollView中嵌套ListView置顶问题
- 【末世旅行之C++】C++中一个冒号和两个冒号的用法
- Codeforces Round #304 (Div. 2) D. Soldier and Number Game
- 利用php获取图片完整Exif信息类 获取图片详细完整信息类
- php实现手机拍照上传头像功能
- php获取文件mime类型Fileinfo等方法
- php接收二进制数据流转换成图片
- php 接收二进制流转换成图片