给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode res = new ListNode(-1, head);
ListNode temp = res;
while (temp != null && temp.next != null) {
if (temp.next.val == val) {
temp.next = temp.next.next;
continue;
}
temp = temp.next;
}
return res.next;
}
public ListNode removeElements(ListNode head, int val) {
//改变头结点位置
while (head != null && head.val == val) {
head = head.next;
}
//有可能全是相同元素,改变万头结点位置后,链表为空,直接返回即可
if (head == null) {
return head;
}
ListNode res = head;
while (head != null && head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
continue;
}
head = head.next;
}
return res;
}
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
if (head.val == val) {
head = removeElements(head.next, val);
} else {
head.next = removeElements(head.next, val);
}
return head;
}
原文:https://www.cnblogs.com/init-qiancheng/p/14617884.html