题目
给定一个已排序的链表,删除所有重复的元素,使得每个元素只出现一次。
解题思路
使用虚拟头节点遍历链表,时间复杂度 O(n)。
C++ 实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
// 避免处理完后为空的情况
ListNode new_head(0, head);
ListNode *cur = &new_head;
// 每次判断都判断两个连续相邻节点
while (cur->next && cur->next->next) {
int val = cur->next->val;
// 相等的话,说明这些相等的都不要
if (cur->next->next->val == val) {
// 进入循环,直到下一个节点不和 val 相等为止
while (cur->next && cur->next->val == val) {
cur->next = cur->next->next;
}
} else {
cur = cur->next;
}
}
return new_head.next;
}
};
Java 实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode new_head = (, head);
new_head;
(cur.next != && cur.next.next != ) {
cur.next.val;
(cur.next.next.val == val) {
(cur.next != && cur.next.val == val) {
cur.next = cur.next.next;
}
} {
cur = cur.next;
}
}
new_head.next;
}
}

