82. Remove Duplicates from Sorted List II
题目
原始地址:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/#/description
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
}
}
描述
删除给定单链表中所有含有重复值的节点,只保留值唯一的节点。
分析
本题的难点在于如何在遍历链表的过程当中记录之前的值以及是否出现过重复的情况,普通的写法会比较繁琐,给出下面两个解法。
解法一使用递归,如果当前值重复就一直跳过,处理出现下一个值时的部分,如果当前值唯一就先把当前值指向后面部分处理的结果,再返回当前值。
解法二使用循环。最精髓的部分在于用prev记录上一个值出现的最后一个节点,用prev.next == curr这个条件来判断是否出现重复值的情况。
解法1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
if (head.next != null && head.val == head.next.val) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
return deleteDuplicates(head.next);
} else {
head.next = deleteDuplicates(head.next);
return head;
}
}
}
解法2
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode curr = head, newHead = new ListNode(0), prev = newHead, newCurr = newHead;
newHead.next = head;
while (curr != null) {
while (curr.next != null && curr.val == curr.next.val) {
curr = curr.next;
}
if (prev.next == curr) {
newCurr.next = curr;
newCurr = newCurr.next;
}
prev = curr;
curr = curr.next;
}
newCurr.next = null;
return newHead.next;
}
}