Write code to remove duplicate nodes from the unordered linked list.
Advanced
What should I do if I cannot use a temporary buffer?
Analysis: Use set to record the accessed values. Time complexity O (N * logn). If unordered_set or hash_set is used, the time complexity is O (n ).
1 #include <iostream> 2 #include <fstream> 3 #include <assert.h> 4 #include <set> 5 6 using namespace std; 7 8 struct Node { 9 Node(): val(0), next(0) {}10 Node( int value ): val(value), next(0) {}11 int val;12 Node *next;13 };14 15 void removeDuplicate( Node *node );16 17 int main( int argc, char *argv[] ) {18 string data_file = "./2.1.txt";19 ifstream ifile( data_file.c_str(), ios::in );20 if( !ifile.is_open() ) {21 fprintf( stderr, "cannot open file: %s\n", data_file.c_str() );22 return -1;23 }24 int n = 0, tmp = 0;25 while( ifile >>n ) {26 assert( n >= 0 );27 Node guard, *node = &guard;28 for( int i = 0; i < n; ++i ) {29 node->next = new Node();30 node = node->next;31 ifile >>node->val;32 cout <<node->val <<" ";33 }34 cout <<endl;35 removeDuplicate( guard.next );36 node = guard.next;37 cout <<"result:" <<endl;38 while( node ) {39 Node *next = node->next;40 cout <<node->val <<" ";41 delete node;42 node = next;43 }44 cout <<endl <<endl;45 }46 ifile.close();47 return 0;48 }49 50 void removeDuplicate( Node *node ) {51 if( !node || !node->next ) { return; }52 set<int> nodeSet;53 Node *end = node, *cur = node->next;54 nodeSet.insert( node->val );55 while( cur ) {56 Node *next = cur->next;57 if( nodeSet.count( cur->val ) ) {58 delete cur;59 } else {60 nodeSet.insert( cur->val );61 end->next = cur;62 end = cur;63 }64 cur = next;65 }66 end->next = 0;67 return;68 }
Advanced requirements do not use temporary buffers. Each time you delete an element in a subsequent sequence that has the same value as the current element. Time complexity O (N ^ 2)
1 void removeDuplicate( Node *node ) { 2 if( !node ) { return; } 3 Node *cur = node; 4 while( cur ) { 5 Node *runner = cur; 6 while( runner->next ) { 7 if( runner->next->val == cur->val ) { 8 Node *next = runner->next; 9 runner->next = next->next;10 delete next;11 } else {12 runner = runner->next;13 }14 }15 cur = cur->next;16 }17 return;18 }
Test File
01121 322 233 2 133 2 342 43 67 25441 52 145 21 245612 421 5645 33 12 421714 54 96 23 45 12 45812 32 34 12 12 12 12 34
Linked List 2.1