Description: The idea is written in pseudo-code, in order to express meaning.
First, delete the list of nodes equal to val
Cur requires two nodes and PREV (as a precursor of the node cur)
to traverse the entire list, and compares a given val,
if they are equal: prev.next = cur.next;
if not equal: cur = cur.next;
Second, after the designated POS insertion, deletion node
is inserted: pos.next = Node;
node.next = pos.next;
Delete: pos.next = pos.next.next
code show as below:
```class Node {
int val;
Node next = null;
Node(int val) {
this.val = val;
}
public String toString() {
return String.format("Node(%d)", val);
}
}
{Solution class
public removeElements the Node (the Node head, int Val) {
the Node result = null;
the Node Last = null; // record the last current result node
Node cur = head;
while (cur != null) {
if (cur.val == val) {
cur = cur.next;
continue;
}
Node next = cur.next;
cur.next = null;
if (result == null) {
result = cur;
} else {
last.next = cur;
}
last = cur;
cur = next;
}
return result;
}
}
public class MyLinkedList {
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);//pos
head.next.next.next = new Node(4);
Node pos = head.next.next;
pushAfter(pos, 100);//在pos之后入100
// 1, 2, 3, 100, 4
}
private static void pushAfter(Node pos, int val) {
Node node = new Node(val);
node.next = pos.next;
pos.next = node;
}
private static void popAfter(Node pos) {
pos.next = pos.next.next;
}
}