Leetcode: Plus One Linked List

Posted neverlandly

tags:

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

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

Use Stack, O(N) space

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode plusOne(ListNode head) {
11         Stack<ListNode> st = new Stack<ListNode>();
12         while (head != null) {
13             st.push(head);
14             head = head.next;
15         }
16         ListNode dummy = new ListNode(-1);
17         int carry = 1;
18         while (!st.isEmpty() || carry!=0) {
19             int num = 0;
20             if (!st.isEmpty()) num += st.pop().val;
21             if (carry != 0) num += carry;
22             ListNode newNode = new ListNode(num%10);
23             newNode.next = dummy.next;
24             dummy.next = newNode;
25             carry = num / 10;
26         }
27         return dummy.next;
28     }
29 }

Two Pointers, O(1) space

i stand for the right-most non-9 bit, where if there‘s a carry, i is incremented and the bits after i will be set 0

 1 public class Solution {
 2     public ListNode plusOne(ListNode head) {
 3         ListNode dummy = new ListNode(0);
 4         dummy.next = head;
 5         ListNode i = dummy;
 6         ListNode j = dummy;
 7         
 8         while (j.next != null) {
 9             j = j.next;
10             if (j.val != 9) {
11                 i = j;
12             }
13         }
14         
15         if (j.val != 9) {
16             j.val++;
17         } else {
18             i.val++;
19             i = i.next;
20             while (i != null) {
21                 i.val = 0;
22                 i = i.next;
23             }
24         }
25         
26         if (dummy.val == 0) {
27             return dummy.next;
28         }
29         
30         return dummy;
31     }
32 }

 

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

Plus One Linked List -- LeetCode

leetcode No369. Plus One Linked List

leetcode No369. Plus One Linked List

leetcode369- Plus One Linked List- medium

[LeetCode] Plus One Linked List 链表加一运算

369. Plus One Linked List