1. 删除链表节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val) {
if (head.next == null) return null;
head = head.next;
return head;
}
ListNode tmp = head;
while(tmp.next != null) {
if (tmp.next.val == val) {
tmp.next = tmp.next.next;
return head;
} else {
tmp = tmp.next;
}
}
return head;
}
}
2. 删除链表中的重复节点
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
解法 1. 递归:相当于从后往前删,记录一个repeatNum ,只要当前的值等于repeatNum ,返回next
class Solution {
private int repeatNum = Integer.MAX_VALUE;
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
// 1. 递归中获取正确的 next
head.next = deleteDuplicates(head.next);
// 2. head 值等于 next , 标记 repeatNum
if(head != null && head.next != null && head.val == head.next.val){
repeatNum = head.val;
}
// 3. head 值为 repeatNum 一律跳过
while(head != null && head.val == repeatNum){
head = head.next;
}
return head;
}
}
解法 2. 非递归:使用快慢节点,慢节点作为哨兵节点处理头节点,快节点处理重复节点
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return head;
ListNode dummy = new ListNode(Integer.MIN_VALUE);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy.next;
while (fast != null) {
while (fast.next != null && fast.val == fast.next.val) fast = fast.next;
if (slow.next == fast) {
// 无重复
slow = slow.next;
} else {
// 有重复,将最后一个重复节点也去除
slow.next = fast.next;
}
fast = fast.next;
}
return dummy.next;
}
}
网友评论