力扣:203. 移除链表元素

This commit is contained in:
huangge1199 2021-02-07 11:42:00 +08:00
parent 5f14194b4c
commit bf339bbbea

View File

@ -0,0 +1,29 @@
package com.code.leet.study.t20210207;
import com.code.leet.entiy.ListNode;
/**
* 删除链表中等于给定值 val 的所有节点
*/
public class RemoveElements {
public ListNode removeElements(ListNode head, int val) {
ListNode temp = head;
if (temp == null) {
return head;
}
while (temp.val == val) {
head = temp = temp.next;
if (temp == null) {
return head;
}
}
while (temp != null && temp.next != null) {
if (temp.next.val == val) {
temp.next = temp.next.next;
} else {
temp = temp.next;
}
}
return head;
}
}