题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
思路:
思路1: 基本思路是先遍历确定重复的数值,然后再遍历一次构造输出的链表。可以采用Hash表结构,每个Hash值需要记录出现的次数;当然也可以采用两个bitmap,一个用来保存出现一次的数值,另一个用来保存出现两次的数值。 思路2: 一次遍历删除所有重复的结点。
代码:
思路1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class bitmap
{
public:
bitmap(int n);
~bitmap();
void set(int k);
bool val(int k);
private:
int len;
unsigned int* map;
unsigned int* reversemap;
bool zero;
};
bitmap::bitmap(int n)
{
len = n/32+1;
map = new unsigned int[len];
reversemap = new unsigned int[len];
for(int i = 0; i < len; i++)
{
map[i] = 0;
reversemap[i] = 0;
zero = false;
}
}
void bitmap::set(int k)
{
bool reverse = true;
if(k== 0)
{
zero = true;
}
else if(k<0)
{
reverse = false;
k =-k;
}
int a = k/32;
int b = k%32;
if(a >= len)
{
return;
}
else
{
if(reverse)
{
int tmp = reversemap[a]/pow(2,b);
if(tmp%2 == 0)
{
reversemap[a] += pow(2,b);
}
}
else
{
int tmp = map[a]/pow(2,b);
if(tmp%2 == 0)
{
map[a] += pow(2,b);
}
}
}
}
bool bitmap::val(int k)
{
bool reverse = true;
if(k== 0)
{
return zero;
}
else if(k<0)
{
reverse = false;
k =-k;
}
int a = k/32;
int b = k%32;
if(a >= len)
{
return false;
}
else
{
if(reverse)
{
int tmp = reversemap[a]/pow(2,b);
if(tmp%2 == 1)
{
return true;
}
else
{
return false;
}
}
else
{
int tmp = map[a]/pow(2,b);
if(tmp%2 == 1)
{
return true;
}
else
{
return false;
}
}
}
}
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL)
{
return NULL;
}
ListNode * p =head;
bitmap* bm = new bitmap(32767);
bitmap* duplicate = new bitmap(32767);
while(p != NULL)
{
if(bm->val(p->val))
{
duplicate->set(p->val);
}
else
{
bm->set(p->val);
}
p = p->next;
};
ListNode * begin = NULL;
p =head;
while(p != NULL)
{
if(!duplicate->val(p->val))
{
begin = p;
break;
}
p = p->next;
};
if(p == NULL)
{
return begin;
}
while(p->next != NULL)
{
if(duplicate->val(p->next->val))
{
p->next = p->next->next;
}
else
{
p = p->next;
}
};
return begin;
}
};
思路2:
/**
* 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) {
ListNode * ptr = new ListNode(INT_MIN);
ptr->next = head;
ListNode * lead = ptr;
int cur = INT_MIN;
while(ptr->next != NULL && ptr->next->next != NULL){
if(ptr->next->val == ptr->next->next->val){
cur = ptr->next->val;
ptr->next->next = ptr->next->next->next;
}
else{
if(ptr->next->val == cur){
ptr-> next = ptr->next->next;
}
else{
ptr = ptr->next;
}
}
}
if(ptr->next != NULL && ptr->next->val == cur){
ptr->next = NULL;
}
return lead->next;
}
};