[C++]LeetCode 2: Add Two Numbers(链表逆序加法)
来源:互联网 发布:ubuntu 切换到命令行 编辑:程序博客网 时间:2024/05/22 07:50
Problem:
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
分析:
两输入链表本身为从低位到高位,故可直接利用加法式进行计算。注意设置链表头。
另若两链表为从高位到低位,可利用DFS深度搜索,利用stack栈来完成。
AC Code (C++) :
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {public://1555 / 1555 test cases passed.//Runtime: 53 msListNode* addTwoNumbers(ListNode* l1, ListNode* l2){if (l1 == NULL)return l2;if (l2 == NULL)return l1;//对应位相加int carry = 0;//进位ListNode pHead(-1);//链表头ListNode *pNode = &pHead;ListNode *pNode1 = l1;ListNode *pNode2 = l2;while (pNode1 != NULL || pNode2 != NULL){int sum = carry;if (pNode1 != NULL && pNode2 != NULL){sum = pNode1->val + pNode2->val + carry;pNode1 = pNode1->next;pNode2 = pNode2->next;}else if (pNode1 != NULL && pNode2 == NULL){sum = pNode1->val + carry;pNode1 = pNode1->next;}else if (pNode1 == NULL && pNode2 != NULL){sum = pNode2->val + carry;pNode2 = pNode2->next;}pNode->next = new ListNode(sum % 10);carry = sum / 10;pNode = pNode->next;}if (carry != 0){pNode->next = new ListNode(carry % 10);carry /= 10;pNode = pNode->next;}return pHead.next;}};
总结:
链表的使用,注意设置链表头
0 0
- [C++]LeetCode 2: Add Two Numbers(链表逆序加法)
- 【leetcode 2】 Add Two Numbers(C++)
- LeetCode2. Add Two Numbers(链表加法)
- #2 Add Two Numbers (链表作加法)
- 第一天 Add Two Numbers(链表加法)
- 2. Add Two Numbers(链表加法)
- [leetcode] add two numbers(大数据加法链表版)
- LeetCode Add Two Numbers(用链表模拟加法)
- [LeetCode-2] Add Two Numbers(链表数据之和)
- LeetCode 2 Add Two Numbers(链表操作)
- 【leetcode-2】Add Two Numbers(C)
- [C语言][LeetCode][2]Add Two Numbers
- [LeetCode#2][C]Add Two Numbers
- leetcode 2:Add Two Numbers(C语言)
- LeetCode 2. Add Two Numbers(C++)
- [C++]LeetCode: 108 Add Two Numbers (反序链表求和)
- [LeetCode] Add Two Numbers(C++)
- LeetCode-445. Add Two Numbers II (JAVA)链表数字加法
- 个人作业
- HDU 1160 FatMouse's Speed
- 初识FishEye
- iOS代码获取所有控件View结构树存到XML查看
- 关于CUDA6.5中newdelete的解读
- [C++]LeetCode 2: Add Two Numbers(链表逆序加法)
- AsyncResult 类的使用
- 先行进位加法
- PyQt5 状态栏
- JAVA滚动条自动下滑到底部
- hdu 1892 See you~
- 《C语言及程序设计》实践参考——有序数组中插入数据
- 《C语言及程序设计》实践参考——二分法解方程
- 《C语言及程序设计》实践参考——工资的排序