Last active
August 29, 2015 14:03
-
-
Save ivycheung1208/08d9198fb0f9b4bda559 to your computer and use it in GitHub Desktop.
CC150 2.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CC150 2.1 | |
* Write code to remove duplicates from an unsorted linked list. | |
* How would you solve this problem if a temporary buffer is not allowed? | |
*/ | |
#include <iostream> | |
#include <list> | |
#include <vector> | |
using namespace std; | |
void removeDup(list<char> &clst) | |
{ | |
vector<bool> flag(256, false); | |
auto begin = clst.begin(), end = clst.end(); | |
while (begin != end) { | |
if (!flag[*begin]) | |
flag[*begin++] = true; // mark as appeard when first time see a character | |
else | |
begin = clst.erase(begin); // remove duplicates | |
} | |
return; | |
} | |
void removeDupBrute(list<char> &clst) | |
{ | |
auto begin = clst.begin(), end = clst.end(); | |
while (begin != end) { | |
auto del = begin; // set runner one element ahead of begin | |
++del; | |
while (del != end) { | |
if (*del != *begin) // remove duplicates | |
++del; | |
else | |
del = clst.erase(del); | |
} | |
++begin; // advance to the next character | |
} | |
return; | |
} | |
int main() | |
{ | |
list<char> clst; | |
char c; | |
while (cin >> c) | |
clst.push_back(c); | |
removeDup(clst); | |
for (auto c : clst) | |
cout << c << " "; | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment