目录
题目描述:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
C++代码
执行用时:8 ms, 在所有 C++ 提交中击败了85.43%的用户
内存消耗:11.2 MB, 在所有 C++ 提交中击败了86.99%的用户
通过测试用例:166 / 166
/**
* 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) {
// 特殊情况:0或者1个
if (head == nullptr || head->next == nullptr) return head;
ListNode* p = head; // 头节点有值
while (p->next != nullptr) // 后面指针指向的不是空,则说明有值
{
if (p->val == p->next->val)
{
// ListNode* temp = p->next; // 保存当前要删除的
p->next = p->next->next; // 跳过当前要删除的
// free(temp); // 释放当前要删除的
// 如果删除了节点,那接下来的节点也需要和p进行比较。
}
else p = p->next;
}
return head; // 头节点有值
}
};
python代码
执行用时:24 ms, 在所有 Python 提交中击败了75.23%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了76.89%的用户
通过测试用例:166 / 166
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 特殊情况
if head is None or head.next is None: return head
p = head # 头节点有值
while p.next is not None:
if p.val == p.next.val:
temp = p.next
p.next = p.next.next
del temp
else: p = p.next
return head