力扣—237.删除链表中的节点
class Solution {
public void deleteNode(ListNode node) {
//判断链表是否为空
if (node == null){
return;
}
//删除node节点并更新链表
node.val = node.next.val;
node.next = node.next.next;
}
}
力扣—83.删除排序链表中的重复元素
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {
return null;
}
ListNode newHead = new ListNode(-1);
ListNode tail = newHead;
ListNode cur = head;
while (cur != null) {
if (cur.next != null && cur.val == cur.next.val) {
while (cur.next != null && cur.val == cur.next.val) {
cur = cur.next;
}
tail.next = cur;//cur为最后一个重复的节点,保留。
} else {
tail.next = cur;
tail = tail.next;
cur = cur.next;
}
}
return newHead.next;
}
}
力扣—82.删除排序链表中的重复元素 II
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode cur = head;
ListNode newHead = new ListNode(-1);
ListNode tmp = newHead;
while (cur != null) {
if (cur.next != null && cur.val == cur.next.val) {
while (cur.next != null && cur.val == cur.next.val) {
cur = cur.next;
}
cur = cur.next;//cur为最后一个重复节点,再走一步,删除。
tmp.next = cur;
} else {
tmp.next = cur;
tmp = tmp.next;
cur = cur.next;
}
}
return newHead.next;
}
}
力扣—203.移除链表元素
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;
cur = prev.next;
} else {
prev = cur;
cur = cur.next;
}
}
//处理头节点
if (head.val == val){
head = head.next;
}
return head;
}
}