zoukankan      html  css  js  c++  java
  • Plus One Linked List -- LeetCode

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

    思路:递归。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     int help(ListNode* head) {
    12         if (head->next == NULL) head->val++;
    13         else head->val += help(head->next);
    14         if (head->val < 10) return 0;
    15         head->val = 0;
    16         return 1;
    17     }
    18     ListNode* plusOne(ListNode* head) {
    19         int credit = help(head);
    20         if (!credit) return head;
    21         ListNode *res = new ListNode(1);
    22         res->next = head;
    23         return res;
    24     }
    25 };
  • 相关阅读:
    17、静态链表
    16、约瑟夫问题
    15、循环链表
    9、插入排序
    14、企业链表
    13、单向链表
    12、顺序表的顺序存储结构
    11、归并排序
    10、快速排序
    原型模式
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5812850.html
Copyright © 2011-2022 走看看