题目
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
分析
可以先处理掉头结点=val的情况,然后因为要删除一个结点,删除一个结点的时候肯定需要知道被删除结点的上一个结点,所以用一个哨兵记录当前结点,一个记录上一个结点,如果当前结点和val相等那么更新上一个结点的next指针,如果不相等那就更新上一个结点
java
public class LinkNode {
int val;
LinkNode next;
public LinkNode(int data) {
this.val = data;
this.next = null;
}
}
public class LinkList {
LinkNode head;
public LinkList() {
this.head = null;
}
public LinkNode getHead() {
return this.head;
}
//添加元素
public void addNode(int data) {
LinkNode node = new LinkNode(data);
if (this.head == null) {
this.head = node;
} else {
LinkNode cur = this.head;
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//正序打印
public void print(LinkNode node) {
while(node != null) {
System.out.print(node.val);
System.out.print(" ");
node = node.next;
}
System.out.println();
}
public void deleteDupl(int val) {
LinkNode p = this.head;
while(this.head != null && this.head.val == val) {
this.head = this.head.next;
}
if(this.head == null) {
return;
}
LinkNode prev = this.head;
LinkNode cur = this.head.next;
while(cur != null) {
if(cur.val == val) {
prev.next = cur.next;
} else {
prev = cur;
}
cur = cur.next;
}
print(this.head);
}
}
public class removeLinkedListElements {
public static void main(String[] args) {
LinkList list = new LinkList();
list.addNode(1);
list.addNode(2);
list.addNode(6);
list.addNode(3);
list.addNode(4);
list.addNode(5);
list.addNode(6);
list.deleteDupl(6);
list = new LinkList();
list.addNode(6);
list.addNode(6);
list.addNode(6);
list.deleteDupl(6);
}
}