标签:head pre com element tno leetcode list move null
package 链表;
/**
* https://leetcode-cn.com/problems/remove-linked-list-elements/
* 203. 移除链表元素
* <p>
* 解题思路 :使用哨兵
*/
public class _203_Remove_Linked_List_Elements {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 新建个节点,防止第一个节点就是要被移除的节点
ListNode sentinel = new ListNode(0);
sentinel.next = head;
// 前一个节点
ListNode prev = sentinel;
// 后一个节点
ListNode curr = head;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
} else {
prev = curr;
}
curr = curr.next;
}
return sentinel.next;
}
}
}
标签:head pre com element tno leetcode list move null
原文地址:https://www.cnblogs.com/jianzha/p/12812254.html