博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
删除链表中重复的节点——重复节点保留一个
阅读量:2382 次
发布时间:2019-05-10

本文共 1214 字,大约阅读时间需要 4 分钟。

题目:

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点保留一个,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->3->4->5

代码1:时间复杂度O(n),空间复杂度O(n)

ListNode* remove(ListNode* head){    if (head == nullptr || head->next == nullptr)        return head;    unordered_set
s; s.insert(head->val); ListNode* pre = head; ListNode* cur = head->next; while (cur != nullptr) { if (s.count(cur->val)) { pre->next = cur->next; cur = cur->next; } else { s.insert(cur->val); pre = pre->next; cur = cur->next; } } return head;}

代码2:时间复杂度O(n^2),空间复杂度O(1)

ListNode* remove(ListNode* head){    if (head == nullptr || head->next == nullptr)        return head;    ListNode* cur = head;    while (cur != nullptr)    {        ListNode* pre = cur;        ListNode* next = cur->next;        while (next != nullptr)        {            if (cur->val == next->val)            {                next = next->next;                pre->next = next;            }            else            {                pre = next;                next = next->next;            }        }        cur = cur->next;    }    return head;}

参考资料:

左程云著《程序员代码面试指南》

转载地址:http://ktwab.baihongyu.com/

你可能感兴趣的文章
关于Objective-C方法签名规则的说明
查看>>
libxml2.dylb 添加后找不到<libxml/tree.h> 头文件
查看>>
关于 [[self class] alloc]的理解
查看>>
Eclipse导入Web项目后代码不报错但项目报错(左上角有红叉)解决方案
查看>>
List、Set、数据结构、Collections
查看>>
Sudoku Solver
查看>>
Combination Sum
查看>>
First Missing Positive
查看>>
Trapping Rain Water
查看>>
Permutation Sequence
查看>>
Valid Number
查看>>
Text Justification
查看>>
Simplify Path
查看>>
Add Two Numbers
查看>>
Longest Substring Without Repeating Characters
查看>>
Median of Two Sorted Arrays
查看>>
Search for a Range
查看>>
罗马数字与阿拉伯数字的相互转化
查看>>
3Sum
查看>>
Next Permutation
查看>>