Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
package leetcode;
import ten.Node;
class ListNode {
ListNode next;
int val;
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class MyLinkedList {
public ListNode headNode = null;
public ListNode tailNode = null;
public ListNode getHeadNode() {
return headNode;
}
public void setHeadNode(ListNode headNode) {
this.headNode = headNode;
}
public ListNode getTailNode() {
return tailNode;
}
public void setTailNode(ListNode tailNode) {
this.tailNode = tailNode;
}
public void addNode(int val) {
ListNode node = new ListNode();
node.setVal(val);
node.setNext(null);
if (headNode == null) {
headNode = node;
tailNode = headNode;
} else {
tailNode.setNext(node);
tailNode = node;
}
}
public void printList() {
for (ListNode node = this.headNode; node != null; node = node.getNext()) {
System.out.println(node.getVal());
}
}
public ListNode removeElements(int val) {
ListNode node = this.headNode;
ListNode nodePre = null;// 保存为前一个节点
while (node != null) {
if (node.val == val) {
if (nodePre == null) {
this.headNode = node.next;
} else {
nodePre.next = node.next;
}
} else {
nodePre = node;
}
node = node.next;
}
return this.headNode;
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.removeElements(1);
list.printList();
}
}

浙公网安备 33010602011771号