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; }
Remove Duplicates from Sorted List--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44775127