首页 > 代码库 > 83.Remove Duplicates from Sorted List(删除链表重复元素,STL容器map)
83.Remove Duplicates from Sorted List(删除链表重复元素,STL容器map)
Given a sorted linked list, delete all duplicates such that each elementappear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
HideTags
Linked List
#pragma once #include<iostream> #include<map> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *deleteDuplicates(ListNode *head) { ListNode* p = head; ListNode* pp = NULL;//指向p的前一个节点 map<int, int> m; map<int, int>::iterator it; while (p) { //find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。 it = m.find(p->val); if (it == m.end())//没找到 { m[p->val] = 1; pp = p; p = p->next; } else//找到,已有,删除p指向的节点 { p = p->next; (*pp).next = p; } } return head; } void main() { ListNode* l1 = new ListNode(1); ListNode* l2 = new ListNode(1); ListNode* l3 = new ListNode(2); ListNode* l4 = new ListNode(3); ListNode* l5 = new ListNode(3); ListNode* l6 = NULL; l1->next = l2; l2->next = l3; l3->next = l4; l4->next = l5; ListNode* result = deleteDuplicates(l1); while (result) { cout << result->val << " "; result = result->next; } cout << endl; system("pause"); }
83.Remove Duplicates from Sorted List(删除链表重复元素,STL容器map)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。