-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathSolution1.java
More file actions
43 lines (34 loc) · 1.04 KB
/
Solution1.java
File metadata and controls
43 lines (34 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 203. Remove Linked List Elements
// https://leetcode.com/problems/remove-linked-list-elements/description/
// 不使用虚拟头结点
// 时间复杂度: O(n)
// 空间复杂度: O(1)
public class Solution1 {
public ListNode removeElements(ListNode head, int val) {
// 需要对头结点进行特殊处理
while(head != null && head.val == val){
ListNode node = head;
head = head.next;
}
if(head == null)
return head;
ListNode cur = head;
while(cur.next != null){
if(cur.next.val == val){
ListNode delNode = cur.next;
cur.next = delNode.next;
}
else
cur = cur.next;
}
return head;
}
public static void main(String[] args) {
int[] arr = {1, 2, 6, 3, 4, 5, 6};
int val = 6;
ListNode head = new ListNode(arr);
System.out.println(head);
(new Solution1()).removeElements(head, val);
System.out.println(head);
}
}