当前位置:网站首页>JZ76 删除链表中重复的结点
JZ76 删除链表中重复的结点
2022-04-23 02:40:00 【Rosita.】
题目链接:删除链表中重复的结点_牛客题霸_牛客网
注意点:
1.考虑头节点重复,所以构造虚拟头节点
1.方法一参考了评论区:申请两个指针的pre和cur,pre指向cur的前一个节点,cur指向当前节点,如果cur和cur->next的val想等,就循环找出所有重复节点的末尾,然后pre跳到不重复的节点上即可,时间和空间复杂度都是O(n)。
2.方法二:哈希去重,记录每个节点出现的次数,大于1的指向下一个节点
目录
方法一:双指针
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
if (!pHead) return NULL;
//创建虚拟头节点,防止第一个节点就重复的问题
ListNode* nhead = new ListNode(0);
nhead->next = pHead;
ListNode* pre= nhead, *cur = pHead;
while(cur){
//相邻节点值相等
if(cur ->next && cur->val == cur->next->val){
//找出所有的相同节点
while(cur->next && cur->val == cur->next->val){
cur = cur->next;
}
cur = cur->next;
//跳过重复节点链接
pre ->next = cur;
}
else{
pre = cur;
cur = cur->next;
}
}
return nhead->next;
}
};
方法二:哈希
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
if (!pHead) return NULL;
//创建虚拟头节点,防止第一个节点就重复的问题
ListNode* nhead = new ListNode(0);
nhead->next = pHead;
ListNode *cur = nhead;
//记录每个节点的个数
unordered_map<int, int> map;
while(cur){
map[cur->val]++;
cur = cur->next;
}
//重新遍历链表,删除重复元素
cur = nhead;
while(cur->next){
if(map[cur->next->val] != 1){
//跳过重复元素
cur->next = cur->next->next;
}else{
cur = cur->next;
}
}
//返回头节点
return nhead->next;
}
};
版权声明
本文为[Rosita.]所创,转载请带上原文链接,感谢
https://blog.csdn.net/pure_dreams/article/details/124350930
边栏推荐
- hack the box optimum靶机
- Looking for a job, writing a resume to an interview, this set of information is enough!
- Day 4 of learning rhcsa
- Six very 6 computer driver managers: what software is good for driver upgrade? Recommended by the best computer driver management software abroad
- A domestic image segmentation project is heavy and open source!
- wordpress 调用指定页面内容详解2 get_children()
- Push data from onenet cloud platform to database
- Suggestion: block reference sorting is in the order of keywords
- 电源电路设计原来是这么回事
- Arduino esp8266 network upgrade OTA
猜你喜欢
随机推荐
PIP install shutil reports an error
Using go language to build web server
[NK] Niuke monthly race 48 D
[untitled]
PHP sorting of interview questions on April 20, 2022
类初始化和实例初始化面试题
谷雨
[chrome extender] content_ Cross domain problem of script
006_ redis_ Jedis quick start
Intelligent agricultural management model
If you want to learn SQL with a Mac, you should give yourself a good reason to buy a Mac and listen to your opinions
Talk about current limiting
How to prevent leakage of operation and maintenance data
Rhcsa day 4 operation
Data warehouse construction table 111111
RT_Thread自问自答
十六、异常检测
认识进程(多线程_初阶)
php+mysql對下拉框搜索的內容修改
013_ Analysis of SMS verification code login process based on session