首页 > 代码库 > 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)