public class Algorithm {
public static void main(String[] args) {
int[] arr = {1, 2, 6, 3, 4, 5, 6};
ListNode head = new ListNode(arr);
System.out.println(head);
System.out.println(new Solution().removeElements(head, 6));
}
}
class Solution {
public ListNode removeElements(ListNode head, int val) {
/**
* 涉及到链表遍历,使用虚拟头节点更方便
*/
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode prev = dummyHead;
while (prev.next != null){
if (prev.next.val == val){
ListNode tem = prev.next;
prev.next = tem.next;
tem.next = null;
}
else {
prev = prev.next;
}
}
return dummyHead.next;
}
}
/**
* ListNode类是节点类
* 其对象只是一个节点,而不是链表
*/
class ListNode {
public int val;
public ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public ListNode(int val) {
this.val = val;
}
public ListNode(){}
/**
* 在构造方法里根据一个数组来构建链表
*/
public ListNode(int[] arr){
if (arr == null || arr.length == 0){
throw new IllegalArgumentException("数组是空的");
}
/**
* this指这个ListNode对象
* 将其设置为这个链表的头节点,就可以根据头节点生成链表了
*/
this.val = arr[0];
ListNode prev = this;
for (int i = 1; i < arr.length; i++) {
prev.next = new ListNode(arr[i]);
prev = prev.next;
}
}
/**
* 当打印头节点对象时,就会打印出整个链表
*/
@Override
public String toString(){
StringBuilder str = new StringBuilder();
ListNode curr = this;
while (curr != null){
str.append(curr.val + "——>");
curr = curr.next;
}
str.append("null");
return str.toString();
}
}
https://leetcode-cn.com/problems/remove-linked-list-elements/