Ch2-4:add reverse 1 digit format number in linked list
来源:互联网 发布:三菱plc编程入门 编辑:程序博客网 时间:2024/04/30 10:04
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
第一个想法是先把linkedlist变为int,相加,再初始化为一个linkedlist,但这样很耗时间:max(O(list1),O(list2))+O(listSUM)=O(listSUM).
第二种就是CC里面给的方法:因为recursive本质就是stack,而stack是LIFO,正好可以反过来,所以就用了这个方法:
node* addlist(node *list1, node * list2, int carry){node* result = new node();int value = carry;if(list1!=NULL)value += list1->data;if(list2!=NULL)value += list2->data;result->data = value % 10;if(list1!=NULL || list2!=NULL || value >= 10){node* more = addlist(list1!=NULL? list1->next: NULL, list2!=NULL? list2->next: NULL, value>=10? 1:0);result->next = more;}return result;}
完整代码在这里。但是有个问题!
输出结果是:
Executing the program....$demo 1 2 9 3 end39219 9 2 end2990 2 2 4 0 end //这里应该输出0 2 2 4 end, 为什么多个0?4220
0 0
- Ch2-4:add reverse 1 digit format number in linked list
- Reverse Linked List II && Add Binary
- Reverse a doubly linked list in O(1) time
- 【Leetcode】Reverse Linked List II in JAVA
- 4-4-Reverse Linked List
- leetCode(1):Reverse Linked List
- Ch2-3: remove the middle node in a singly linked list
- Ch2-5: find the beginning of loop in a circular linked list---two solutions
- 【Linked-list专题-2】237. Delete Node in a Linked List 206. Reverse Linked List
- PTA 4-4 Reverse Linked List
- FW:Reverse a Singly Linked List Recursively in Java
- LeetCode[Linked List]: Reverse Nodes in k-Group
- Linked List-----25. Reverse Nodes in k-Group
- Single linked list reverse
- reverse a linked list
- Reverse a linked list.
- Reverse a linked list
- Reverse Linked List II
- WinCE之TCP编程——服务器端
- [转帖]一个华为哥们学习&开发GSM的一些事
- 用3个步骤实现响应式网页设计
- CHECKSUM 和 Tempdb
- iOS 设备的屏幕尺寸、分辨率及其屏幕边长比例详细情况是怎样的?
- Ch2-4:add reverse 1 digit format number in linked list
- WinCE之TCP编程——客户端
- PetaBricks 安装
- JDBC连接MySQL数据库及示例
- STL-vector与list的区别
- 组合数学合集
- 送她的光立方
- A Pocketful of Pigs
- 4g slim开机后看到主机后面的spdif接口里面亮了个红灯,这是正常现象吗?yvj