题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
思路:和数组删除很相似
#include <iostream>
#include <vector>
using namespace std;
typedef struct list_node List;
struct list_node
{
int value;
struct list_node* next;
};
void Init_List(List*& head,int* array,int n)
{
head = NULL;
List* tmp;
List* record;
for(int i=1;i<=n;i++)
{
tmp = new List;
tmp->next = NULL;
tmp->value = array[i-1];
if(head == NULL)
{
head = tmp;
record = head;
}
else
{
record->next = tmp;
record = tmp;
}
}
}
void print_list(List* list)
{
List* tmp=list;
while(tmp != NULL)
{
cout<<tmp->value<<endl;
tmp = tmp->next;
}
}
void RemoveDuplicate(List*& head)
{
if(head == NULL || head->next==NULL)
return ;
List* low= head;
List* fast = head->next;
List* tmp;
while(fast != NULL)
{
if(low->value == fast->value)
{
tmp = fast;
fast = fast->next;
low->next = fast;
delete tmp;
}
else
{
low = low->next;
fast = fast->next;
}
}
}
int main()
{
int array[]={1,1,1,2,3,3,4,5,6,6,7,7};
List* head;
Init_List(head,array,sizeof(array)/sizeof(int));
RemoveDuplicate(head);
print_list(head);
return 0;
}
上述的方法比较繁琐
List* removeDuplicate(List* head)
{
if(head == NULL || head->next == NULL)
return head;
List* temp,*pre,*cur;
List* newhead = new List;
newhead->next = head;
temp = newhead;
pre = head;
cur= head->next;
while(cur != NULL)
{
while(cur != NULL && cur->value == pre->value)
cur = cur->next;
if(pre->next == cur)
{
temp->next = pre;
temp = pre;
pre = cur;
// cur = cur->next;
}
else
{
pre= cur;
// cur = cur->next;
}
if(cur != NULL)
cur = cur->next;
}
temp->next = cur;
return newhead->next;
}
有些时候在处理链表的题目中,使用一个临时链表节点会使得处理过程非常简单,在上述的这个处理过程中即可发现。
虽说使用伪指针可以很方便解决这个问题,但是上述代码并不是很完美,因为没有释放节点,我们可以考虑一直往pre之后插入,所以遍历的指针cur一直在pre的下一个指针,如果pre->value == cur->value 那么pre->next = cur->next;delete cur,cur= pre->next, 是的cur始终为pre的下一个指针。