[Leetcode] 369. Plus One Linked List 解题报告
来源:互联网 发布:apache hadoop怎么读 编辑:程序博客网 时间:2024/06/05 21:49
题目:
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example:
Input:1->2->3Output:1->2->4
思路:
可以递归实现:如果该结点的下一个结点是空,说明到了链表尾部,就直接加1,并处理进位情况;否则递归调用该结点的下一个节点;如果有进位,则还需要对当前结点进行加1操作,并且最终返回是否在当前位需要进位。注意如果head结点为空需要特殊处理。该算法本身的时间复杂度是O(n),空间复杂度是O(1),但是由于递归调用占用栈空间,所以运行中的时间复杂度是O(n)。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* plusOne(ListNode* head) { if (head == NULL) { return new ListNode(1); } int remain = addOne(head); if (remain == 0) { return head; } else { ListNode* new_head = new ListNode(1); new_head->next = head; return new_head; } }private: int addOne(ListNode* node) { // precondition: node cannot be NULL int remain = 0; if (node->next == NULL) { if (++node->val >= 10) { node->val -= 10; remain = 1; } } else { node->val += addOne(node->next); if (node->val >= 10) { node->val -= 10; remain = 1; } } return remain; }};
阅读全文
0 0
- [leetcode] 369. Plus One Linked List 解题报告
- [Leetcode] 369. Plus One Linked List 解题报告
- LeetCode 369. Plus One Linked List
- [leetCode] 369. Plus One Linked List
- [LeetCode] Plus One 解题报告
- 【LeetCode】Plus One 解题报告
- LeetCode 369. Plus One Linked List(链表加1)
- Leetcode 369. Plus One Linked List (Medium) (cpp)
- LeetCode Plus One Java版解题报告
- [leetcode] 66. Plus One 解题报告
- [Leetcode] 66. Plus One 解题报告
- Plus One Linked List
- LeetCode — Linked List Cycle 解题报告
- [LeetCode]Reverse Linked List II, 解题报告
- [LeetCode OJ] Linked List Cycle 解题报告
- [LeetCode]Reverse Linked List II解题报告
- 【LeetCode】Reverse Linked List II 解题报告
- LeetCode-Reverse Linked List-解题报告
- Linux vi/vim编辑器常用命令与用法总结
- linux kali 下安装 微 信
- SPOJ375[QTREE
- 【USACO TRAINING】子集的和
- 京东轮播图
- [Leetcode] 369. Plus One Linked List 解题报告
- Android自定义Transition动画
- 《深入理解java虚拟机》学习-第八章-虚拟机字节码执行引擎-运行时栈帧结构
- iOS开发-获取设备IP
- 解决spring请求中文乱码问题
- 高性能web服务器nginx
- VS2010 无可用源
- RecyclerView自定义LayoutManager,打造不规则布局
- Hibernate—(HQL查询)