p80 链表加一(leetcode 369)

喜你入骨 提交于 2020-04-04 17:50:45

一:解题思路

采用一个虚拟的头节点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;
        }
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!