42
42
43
43
<!-- 这里可写通用的实现逻辑 -->
44
44
45
- 找出链表最右一个 ` val ≠ 9 ` 的节点 target,将 target 值加 1。然后将 target 之后的所有节点值置为 0。
45
+ ** 方法一:链表遍历 **
46
46
47
- 若遇到如 ` 9 -> 9 -> 9 ` 的链表,就找不到 target 了,因此,我们可以定义一个虚拟头节点 dummy,初始值为 0。刚开始将 target 指向 dummy,这样就确保链表一定存在一个 ` val ≠ 9 ` 的节点了。
47
+ 我们先设置一个虚拟头节点 ` dummy ` ,初始值为 $0$,指向链表头节点 ` head ` 。
48
+
49
+ 然后从链表头节点开始遍历,找出链表最后一个值不等于 $9$ 的节点 ` target ` ,将 ` target ` 的值加 $1$。接着将 ` target ` 之后的所有节点值置为 $0$。
50
+
51
+ 需要注意的是,如果链表中所有节点值都为 $9$,那么遍历结束后,` target ` 会指向空节点,这时我们需要将 ` dummy ` 的值加 $1$,然后返回 ` dummy ` ,否则返回 ` dummy ` 的下一个节点。
52
+
53
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为链表的长度。
48
54
49
55
<!-- tabs:start -->
50
56
60
66
# self.next = next
61
67
class Solution :
62
68
def plusOne (self , head : ListNode) -> ListNode:
63
- dummy = ListNode(val = 0 , next = head)
69
+ dummy = ListNode(0 , head)
64
70
target = dummy
65
71
while head:
66
72
if head.val != 9 :
@@ -99,7 +105,7 @@ class Solution {
99
105
}
100
106
head = head. next;
101
107
}
102
- target. val += 1 ;
108
+ ++ target. val;
103
109
target = target. next;
104
110
while (target != null ) {
105
111
target. val = 0 ;
@@ -110,6 +116,71 @@ class Solution {
110
116
}
111
117
```
112
118
119
+ ### ** C++**
120
+
121
+ ``` cpp
122
+ /* *
123
+ * Definition for singly-linked list.
124
+ * struct ListNode {
125
+ * int val;
126
+ * ListNode *next;
127
+ * ListNode() : val(0), next(nullptr) {}
128
+ * ListNode(int x) : val(x), next(nullptr) {}
129
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
130
+ * };
131
+ */
132
+ class Solution {
133
+ public:
134
+ ListNode* plusOne(ListNode* head) {
135
+ ListNode* dummy = new ListNode(0, head);
136
+ ListNode* target = dummy;
137
+ while (head) {
138
+ if (head->val != 9) target = head;
139
+ head = head->next;
140
+ }
141
+ ++target->val;
142
+ target = target->next;
143
+ while (target) {
144
+ target->val = 0;
145
+ target = target->next;
146
+ }
147
+ return dummy->val == 1 ? dummy : dummy->next;
148
+ }
149
+ };
150
+ ```
151
+
152
+ ### **Go**
153
+
154
+ ```go
155
+ /**
156
+ * Definition for singly-linked list.
157
+ * type ListNode struct {
158
+ * Val int
159
+ * Next *ListNode
160
+ * }
161
+ */
162
+ func plusOne(head *ListNode) *ListNode {
163
+ dummy := &ListNode{0, head}
164
+ target := dummy
165
+ for head != nil {
166
+ if head.Val != 9 {
167
+ target = head
168
+ }
169
+ head = head.Next
170
+ }
171
+ target.Val++
172
+ target = target.Next
173
+ for target != nil {
174
+ target.Val = 0
175
+ target = target.Next
176
+ }
177
+ if dummy.Val == 1 {
178
+ return dummy
179
+ }
180
+ return dummy.Next
181
+ }
182
+ ```
183
+
113
184
### ** ...**
114
185
115
186
```
0 commit comments