File tree Expand file tree Collapse file tree 1 file changed +30
-24
lines changed Expand file tree Collapse file tree 1 file changed +30
-24
lines changed Original file line number Diff line number Diff line change @@ -224,35 +224,33 @@ struct ListNode* removeElements(struct ListNode* head, int val){
224
224
225
225
### Java:
226
226
227
+ 用原来的链表操作:
227
228
```java
228
229
/**
229
- * 添加虚节点方式
230
+ * 方法1
230
231
* 时间复杂度 O(n)
231
232
* 空间复杂度 O(1)
232
233
* @param head
233
234
* @param val
234
235
* @return
235
236
*/
236
237
public ListNode removeElements(ListNode head, int val) {
237
- if (head == null ) {
238
- return head;
238
+ while (head!=null && head.val==val ) {
239
+ head = head.next ;
239
240
}
240
- // 因为删除可能涉及到头节点,所以设置dummy节点,统一操作
241
- ListNode dummy = new ListNode(-1, head);
242
- ListNode pre = dummy;
243
- ListNode cur = head;
244
- while (cur != null) {
245
- if (cur.val == val) {
246
- pre.next = cur.next;
241
+ ListNode curr = head;
242
+ while(curr!=null && curr.next !=null) {
243
+ if(curr.next.val == val){
244
+ curr.next = curr.next.next;
247
245
} else {
248
- pre = cur ;
246
+ curr = curr.next ;
249
247
}
250
- cur = cur.next;
251
248
}
252
- return dummy.next ;
249
+ return head ;
253
250
}
251
+
254
252
/**
255
- * 不添加虚拟节点方式
253
+ * 方法1
256
254
* 时间复杂度 O(n)
257
255
* 空间复杂度 O(1)
258
256
* @param head
@@ -280,27 +278,35 @@ public ListNode removeElements(ListNode head, int val) {
280
278
}
281
279
return head;
282
280
}
281
+
282
+ ```
283
+
284
+ 设置一个虚拟头结点:
285
+
286
+ ``` java
283
287
/**
284
- * 不添加虚拟节点and pre Node方式
285
288
* 时间复杂度 O(n)
286
289
* 空间复杂度 O(1)
287
290
* @param head
288
291
* @param val
289
292
* @return
290
293
*/
291
294
public ListNode removeElements(ListNode head, int val) {
292
- while(head!=null && head.val==val){
293
- head = head.next;
294
- }
295
- ListNode curr = head;
296
- while(curr!=null){
297
- while(curr.next!=null && curr.next.val == val){
298
- curr.next = curr.next.next;
295
+ // 设置一个虚拟的头结点
296
+ ListNode dummy = new ListNode ();
297
+ dummy. next = head;
298
+
299
+ ListNode cur = dummy;
300
+ while (cur. next != null ) {
301
+ if (cur. next. val == val) {
302
+ cur. next = cur. next. next;
303
+ } else {
304
+ cur = cur. next;
299
305
}
300
- curr = curr.next;
301
306
}
302
- return head ;
307
+ return dummy . next ;
303
308
}
309
+
304
310
```
305
311
306
312
### Python:
You can’t perform that action at this time.
0 commit comments