一:解题思路
采用一个虚拟的头节点maybe,同时用另外一个节点notNine指向maybe。然后考虑的情况和上道题数组加一基本上是一样的。Time:O(n),Space:O(1)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: ListNode * plusOne(ListNode * head) { ListNode* mayBe = new ListNode(0); ListNode* notNine = mayBe; mayBe->next = head; for (ListNode* p = head; p != NULL; p = p->next) if (p->val != 9) notNine = p; notNine->val += 1; for (ListNode* p = notNine->next; p != NULL; p = p->next) p->val = 0; if (mayBe == notNine) return mayBe; else return head; } };
Java:
public class Solution { public ListNode plusOne(ListNode head) { ListNode maybe=new ListNode(0); ListNode notNine=maybe; maybe.next=head; for(ListNode p=head;p!=null;p=p.next) if(p.val!=9) notNine=p; notNine.val+=1; for(ListNode p=notNine.next;p!=null;p=p.next) p.val=0; if(maybe==notNine) return maybe; else return head; } }
来源:https://www.cnblogs.com/repinkply/p/12632555.html