1. 对应力扣题目连接
2. 实现案例代码
public class RemoveLinkedListElements {
public static void main(String[] args) {
ListNode head1 = new ListNode(1, new ListNode(2, new ListNode(6, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6)))))));
ListNode result1 = removeElements(head1, 6);
printList(result1);
}
public static ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current.next != null) {
if (current.next.val == val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return dummy.next;
}
private static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val);
current = current.next;
if (current != null) {
System.out.print(" -> ");
}
}
System.out.println();
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}