203 移除数组元素

203. 移除链表元素 - 力扣(Leetcode)

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

//移除链表元素 203
public class RemoveLinkedListElements203 {
public static void main(String[] args){
int[] arr = {3,1,2,3,4,3};
ListNode head = initLinkedList(arr);
head = removeElements(head,3);
printLinkedList(head);
}

/**
* 虚拟节点方案
* @head 链表头节点
* @val 删除元素
* @return 被删除节点
*/
public static ListNode removeElements(ListNode head, int val) {
//安全性校验
if (head == null){
return head;
}
ListNode dummy = new ListNode(-1,head);
ListNode pre = dummy;
ListNode cur = head;

while(cur != null){
if (cur.val == val) {
pre.next = cur.next;
}else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}

public static ListNode initLinkedList(int[] nums){
ListNode head = new ListNode(nums[0]);
ListNode pre = head;
ListNode cur;
for(int i = 1; i < nums.length; i++){
cur = new ListNode(nums[i]);
pre.next = cur;
pre = cur;
}
return head;
}

public static void printLinkedList(ListNode head){
ListNode cur = head;
while (cur != null){
System.out.print(cur.val + " -> ");
cur = cur.next;
}
}
}

class ListNode {
int val;//节点的值
ListNode next;

public ListNode (){}

public ListNode (int val){
this.val = val;
}

public ListNode (int val, ListNode next){
this.val = val;
this.next = next;
}
}