leetcode No369. Plus One Linked List

Posted Dufre.WC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode No369. Plus One Linked List相关的知识,希望对你有一定的参考价值。

Question

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

Algorithm

看的题解,有一个好的思路
最不好处理的是带9的case,比如199 + 1 = 200,这里专门用一个指针记录最早9->0的位置。

  • slowfast两个指针
    • slow:记录9的位置
    • fast:正常遍历的指针
  • fast->val等于9的时候,slow不动
  • fast->val不等于9的时候,slow移动到fast
  • 遍历结束,slow的值+1slow后面的都归0

Code

/**
 * 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) 
        ListNode* slow = new ListNode(0);
        slow->next=head;
        ListNode* fast = head;

        while(fast)
            if (fast->val != 9)
                slow = fast;
            
            fast = fast->next;
              
        slow->val += 1; 
        ListNode* tmp = slow->next;
        while(tmp)
            tmp->val = 0;
            tmp = tmp->next;
        
        return slow->next==head?slow:head;
    
;

以上是关于leetcode No369. Plus One Linked List的主要内容,如果未能解决你的问题,请参考以下文章

leetcode369- Plus One Linked List- medium

369. Plus One Linked List

[LeetCode] NO. 66 Plus One

369. Plus One Linked List

369. Plus One Linked List

java 369. Plus One Linked List(Recursive).java