题目描述:
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
利用散列表(哈希表)遍历链表
散列表知识:散列表
C++代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
if(head==NULL)
{
return NULL;
}
else
{
unordered_set<int>set;//建立一个哈希set的容器,set<int>set也可以但是效率比较低。
ListNode*p=head;
while(p!=NULL&&p->next!=NULL)
{
set.insert(p->val);//把链表的第一个元素放进容器
if(set.count(p->next->val)==1)//查找链表的下一个元素是否在容器出现,如果出现(即等于1)就把这个元素删除。
{
p->next=p->next->next;
}
else
{
p=p->next;
}
}
return head;
}
}
};
JAVA 代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head==null||head.next==null){
return head;
}
LinkedHashSet<Integer> set = new LinkedHashSet<>();
ListNode p=head;
set.add(p.val);
while(p.next!=null&&p!=null){
if(set.contains(p.next.val)){
p.next=p.next.next;
} else {
set.add(p.next.val);
p=p.next;
}
}
return head;
}
}
执行结果: