删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
//判断链表是否为空
if (head == null){
return null;
}
//处理非头节点
ListNode prev = head;
ListNode cur = head.next;
while (cur != null){
if (cur.val == val){
prev.next = cur.next; //将prev节点指向cur下一个节点
cur = prev.next;//更新cur
} else {
prev = cur;
cur = cur.next;
}
}
//处理头节点
if (head.val == val){
head = head.next;
}
return head;
}
}
运行结果如下: