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的位置。
slow
,fast
两个指针slow
:记录9
的位置fast
:正常遍历的指针
fast->val
等于9的时候,slow
不动fast->val
不等于9的时候,slow
移动到fast
处- 遍历结束,
slow
的值+1
,slow
后面的都归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的主要内容,如果未能解决你的问题,请参考以下文章