Plus One Linked List
2016-08-03 00:44
357 查看
Given a non-negative number represented as a singly linked list of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Example:
reference: https://discuss.leetcode.com/topic/49647/reverse-plus-one-then-reverse
解法二:寻找从右边到左边的第一个非9的node
reference:https://discuss.leetcode.com/topic/49867/concise-java-iterative-solution
解法三:DFS
reference: https://discuss.leetcode.com/topic/49541/java-recursive-solution
The digits are stored such that the most significant digit is at the head of the list.
Example:
Input: 1->2->3 Output: 1->2->4 解法一:reverse
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode plusOne(ListNode head) { head = reverse(head); ListNode dummy = new ListNode(0); dummy.next = head; ListNode x = dummy; int carry = 1; while (carry > 0 || x.next != null) { if (x.next != null) { x = x.next; carry += x.val; x.val = carry % 10; carry /= 10; } else { x.next = new ListNode(carry); x = x.next; carry = 0; } } return reverse(dummy.next); } public ListNode reverse(ListNode head){ if (head == null) return head; ListNode pre = null; ListNode cur = head; while(cur.next!=null){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } cur.next = pre; return cur; } }
reference: https://discuss.leetcode.com/topic/49647/reverse-plus-one-then-reverse
解法二:寻找从右边到左边的第一个非9的node
public ListNode plusOne(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode runner = dummy; ListNode pointer = dummy; //from right to left, find the first digit that is not 9; while(runner.next != null) { runner = runner.next; if(runner.val != 9) pointer = runner; } pointer.val = pointer.val + 1; runner = pointer.next; while(runner != null) { runner.val = 0; runner = runner.next; } return pointer == dummy? dummy : head; }
reference:https://discuss.leetcode.com/topic/49867/concise-java-iterative-solution
解法三:DFS
public ListNode plusOne(ListNode head) { if( DFS(head) == 0){ return head; }else{ ListNode newHead = new ListNode(1); newHead.next = head; return newHead; } } public int DFS(ListNode head){ if(head == null) return 1; int carry = DFS(head.next); if(carry == 0) return 0; int val = head.val + 1; head.val = val%10; return val/10; }
reference: https://discuss.leetcode.com/topic/49541/java-recursive-solution
相关文章推荐
- 最大子数组
- ACM-括号配对问题
- java回忆录—运算符
- poj 3680 Intervals(巧妙构图,费用流)
- 丘成桐数学竞赛2016
- 顺序单链表插入新节点的一种方法
- SpringMVC参数传递一
- 剪切板clipboard
- MySQL入门经典-----10、MySQL事务(让程序听话)
- Unity 法线翻转
- 利用面向对象的思想实现一套代码,要求一个APP支持微信支付,支付宝支付,银联支付
- MySQL入门经典-----9、MySQL视图(虚拟世界)
- Qt qml ListView 鼠标点击高亮,缩放等基础设置
- C++课程设计之大整数类
- MySQL入门经典-----8、触发器(定时炸弹)
- hdu 2089 不要62 数位dp
- offsetLeft,scrollLeft,offsetTop,scrollTop等等的用法
- MySQL入门经典-----7、MySQL存储过程(一次编写多次调用)
- 师生帮手(4)
- SPOJ-694-求字符串中不同子串个数(后缀数组)