首页 > 代码库 > Leetcode: Plus One Linked List

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