题目描述
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。返回同样按升序排列的结果链表。
- 地址:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
-
法一:直接遍历链表
easy题直接重拳出击
- 新建一个哑节点,指向head;
- 再新建一个cur,移动cur 和 head判断是否需要加入链表
- val值相等则直接前移head,否则都前移
- 时间复杂度 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 or not head.next:return headdummy = ListNode(101)cur = dummywhile head:if cur.val != head.val:cur.next = headcur = cur.nexthead = head.nextcur.next = Nonereturn 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) {ListNode* dummy = new ListNode(101, head);ListNode* cur = dummy;if (!head || !head->next) return head;while (head) {if (cur->val != head->val) {cur->next = head;cur = cur->next;}head = head->next;}cur->next = nullptr;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 作为头继续递归head.next = self.deleteDuplicates(head.next)else: # 否则的话跳过相同的元素,将遇到的第一个不同的节点作为head进行递归move = head.nextwhile move.next and head.val == move.next.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 = new ListNode(0);move = head->next;while (move->next && head->val == move->next->val) {move = move->next;}return deleteDuplicates(move);}return head;}};
