题目描述
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。返回同样按升序排列的结果链表。
- 地址:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
-
法一:直接遍历链表
因为head有可能会被删除,新建一个虚拟节点指向head进行遍历
- 依题意链表是有序的,若相同必定出现在相邻的位置
- 即 cur->next == cur->next->next 时就应该删除该节点,并用一个变量 tmp 记录下被删除的节点的值,用于判断->next->next->next是否需要删除
- 时间复杂度 O(n)
空间复杂度 O(1)
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution(object):def deleteDuplicates(self, head):if not head:return headdummy = ListNode(0, head)cur = dummywhile cur.next and cur.next.next:if cur.next.val == cur.next.next.val:tmp = cur.next.valwhile cur.next and cur.next.val == tmp:cur.next = cur.next.nextelse:cur = cur.nextreturn dummy.next
/*** 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) {if (!head) return head;ListNode* dummy = new ListNode(0, head); // 新建一个指向head的值为0的dummy节点ListNode* cur = dummy;while (cur->next && cur->next->next) { // 一开始就是原链表头节点和头节点的下一个节点if (cur->next->val == cur->next->next->val) { // 相邻的两个节点值相等int tmp = cur->next->val; // 记录下节点的值while ((cur->next) && (cur->next->val == tmp)) { // cur 前移cur->next = cur->next->next;}}else {cur = cur->next;}}return dummy->next;}};
法二:递归
递归终止条件head为空 或者 只有一个节点,return head
- 若相邻的不相等,那么递归head->next
- 若相邻的相等,那么就递归移动后的,所以要判断一下
- 时间复杂度:O(n)
空间复杂度:O(n)
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution(object):def deleteDuplicates(self, head):if not head or not head.next:return headif head.val != head.next.val:head.next = self.deleteDuplicates(head.next)else:move = head.nextwhile move and head.val == move.val:move = move.nextreturn self.deleteDuplicates(move)return head
/*** 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) {if (!head || !head->next) {return head;}if (head->val != head->next->val) {head->next = deleteDuplicates(head->next);}else {ListNode* move = head->next;while (move && head->val == move->val) {move = move->next;}return deleteDuplicates(move);}return head;}};
