题目:
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
原题的力扣链接
https://leetcode.cn/problems/remove-linked-list-elements/description/
解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return null;
}
ListNode pre = head;
ListNode cur = head.next;
while(cur != null){
if(cur.val == val){
cur= cur.next;
pre.next = cur;
}else{
cur = cur.next;
pre = pre.next;
}
//但是一开始的头结点还没处理
if(head.val == val){
head = head.next;
}
//注意这个对头结点的判断一定是放在最后的吧,不然就是不对的,如果放在开头那么新的头结点还是不能判断
}
return head;
}
}