package com.example.nanchen.algorithm;
import com.example.nanchen.entity.ListNode;
public class RemoveLinkListElements {
public static void main(String[] args) {
ListNode head = ListNode.create(false,1,2,1,4,5);
ListNode listNode = remove(head, 1);
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
public static ListNode delete(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
if (head == null) {
return head;
}
ListNode cur = head;
ListNode curNext = cur.next;
while (curNext != null) {
if (curNext.val == val) {
cur.next = curNext.next;
}else {
cur = curNext;
}
curNext = curNext.next;
}
return head;
}
public static ListNode remove(ListNode head, int val) {
ListNode virtualNode = new ListNode(-1, head);
ListNode cur = virtualNode;
ListNode curNext = cur.next;
while (curNext != null) {
if (curNext.val == val) {
cur.next = curNext.next;
}else {
cur = curNext;
}
curNext = curNext.next;
}
return virtualNode.next;
}
}
package com.example.nanchen.entity;
public class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public static ListNode create(boolean virtualHead,int...vals){
ListNode head;
int i;
if (virtualHead) {
head = new ListNode(-1);
i = 0;
}else {
head = new ListNode(vals[0]);
i = 1;
}
ListNode trail = head;
while (i < vals.length) {
ListNode nextListNode = new ListNode(vals[i]);
trail.next = nextListNode;
trail = nextListNode;
i++;
}
return head;
}
}