369. Plus One Linked List

369- Plus One Linked List
**Question
Editorial Solution

My Submissions

Total Accepted: 1189
Total Submissions: 2373
Difficulty: Medium

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:
Input:1->2->3Output:1->2->4

Hide Company Tags
Google
Hide Tags
Linked List
Hide Similar Problems
(E) Plus One


 public ListNode plusOne(ListNode head) {
  /*
   * At the first glance, I want to reverse the inputs, add one, then
   * reverse back. But that is too intuitive and I don't think this is an
   * expected solution. Then what kind of alg would adding one in reverse
   * way for list?
   * 
   * Recursion! With recursion, we can visit list in reverse way! So here is my
   * recursive solution.
   * https://discuss.leetcode.com/topic/49541/java-recursive-solution
   */
  if (dfs(head) == 0) {
   return head;
  } else {
   ListNode newHead = new ListNode(1);
   newHead.next = head;
   return newHead;
  }
 }

 // Recursion solution
 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;
 }
    原文作者:billyzhang
    原文地址: https://www.jianshu.com/p/c3eecb20c72d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞