Skip to content

Instantly share code, notes, and snippets.

@Se7soz
Last active May 12, 2017 20:44
Show Gist options
  • Select an option

  • Save Se7soz/8414342 to your computer and use it in GitHub Desktop.

Select an option

Save Se7soz/8414342 to your computer and use it in GitHub Desktop.
Read the How to prepare for an interview series at my blog: http://se7so.blogspot.com/2014/01/how-to-prepare-for-interview.html
struct List {
int a;
List* nxt;
List(int a) {
this->a = a;
nxt = NULL;
}
void insert(int s) {
List* x = this;
while(x->nxt != NULL) x = x->nxt;
x->nxt = new List(s);
}
List* search(int a) {
List* x = this;
while(x != NULL) {
if(x->a == a) return x;
x = x->nxt;
}
return x;
}
List* deleteNode(int a) {
if(this->a == a) {
List* root = this->nxt;
this->nxt = NULL;
delete this;
return root;
}
List* l = this;
while(l->nxt != NULL) {
if(l->nxt->a == a) {
l->nxt = l->nxt->nxt;
break;
}
l = l->nxt;
}
return this;
}
void deleteDuplicates() {
set<int> found;
List* l = this;
found.insert(l->a);
while(l->nxt) {
if(found.find(l->nxt->a) != found.end()) {
l->nxt = l->nxt->nxt;
}
else {
found.insert(l->nxt->a);
l = l->nxt;
}
}
}
List* reverse() {
if(this->nxt == NULL) return this;
List* l = this->nxt->reverse();
this->nxt->nxt = this;
this->nxt = NULL;
return l;
}
void print() {
List* l = this;
while(l != NULL) {
cout << l->a << " ";
l = l->nxt;
}
cout << endl;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment