1.题目
2.解法(遍历法)
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
// 记得pHead.next == null,return null,这只针对特定链表,不用在哪里都用
if(pHead == null){
return null;
}
// 利用虚假头结点
ListNode head = new ListNode(-1);
head.next = pHead;
ListNode pre = head;
ListNode dup = head;
ListNode move = head.next;
boolean isE = false;
while(move.next != null){
dup = dup.next;
move = move.next;
if(dup.val == move.val){
isE = true;
}else{
if(isE) {
pre.next = move;
isE = false;
}else{
pre = pre.next;
}
}
}
// 注意两类情况:1.{111111} 2.{12344} 全是重复结点,在中间,在末尾
if(isE){
pre.next = null;
}
return head.next;
}
}
时间复杂度为O(n),空间复杂度为O(1)
以下解法也一样
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null){
return null;
}
// 利用虚假头结点
ListNode head = new ListNode(-1);
head.next = pHead;
ListNode pre = head;
ListNode move = head.next;
while(move != null) {
if (move.next != null && move.val == move.next.val) {
move = move.next;
// 将重复结点移动完
while (move.next != null && move.val == move.next.val) {
move = move.next;
}
move = move.next;
pre.next = move;
} else {
pre = pre.next;
move = move.next;
}
}
return head.next;
}
}