-
题目
-
Code
方法1:利用STL容器set来去重,之后将值赋回给原链表
踩坑:最后一个节点的边界注意,否则会多链接一个原链表后面的节点
![在这里插入图片描述](https://img-blog.csdnimg.cn/2019071722364252.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2JyeWFudF94dw==,size_16,color_FFFFFF,t_70/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL) return NULL; set<int> st; ListNode* cur = head; ListNode* res = NULL; while(cur){ st.insert(cur->val); cur = cur->next; } int i = 0; int size = st.size(); cout<<size<<endl; res = head; auto it = st.begin(); while(it != st.end()&&i<size){ cout<<*it<<"->"; head->val = *it; ++it,++i; if(i != size){ head = head->next; } } head -> next = NULL; return res; } };
方法2:时间和空间都有优化,没有开辟O(n)的额外空间。因为已经排序了的,所以遍历相邻的节点值是否相同,相同则跳过即可,不同就next
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL) return NULL; ListNode* cur = head; while(cur && cur->next){ if(cur->val == cur->next->val){ ListNode* tmp = cur->next; cur->next = tmp->next; tmp->next = NULL; }else{ cur = cur->next; } } return head; } };
【LeetCode 83】删除排序链表中的重复元素
最新推荐文章于 2020-03-12 18:45:59 发布