Skip to content

Instantly share code, notes, and snippets.

@unreadable
Last active May 31, 2023 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unreadable/fcf83725fb80a6790a43426940644523 to your computer and use it in GitHub Desktop.
Save unreadable/fcf83725fb80a6790a43426940644523 to your computer and use it in GitHub Desktop.
C++ Template List Implementation
#include <iostream>
template <typename T>
struct Node {
T data;
Node *next;
};
template <typename T> class List{
private:
Node<T> *head;
public:
List(){
head = NULL;
}
void push(T val){
Node<T> *n = new Node<T>();
n->data = val;
n->next = head;
head = n;
}
T pop(){
if(head) {
T p = head->data;
head = head->next;
return p;
}
}
bool search(T val) {
Node<T> *temp = head;
while(temp->next) {
if(temp->data == val) return true;
else temp = temp->next;
}
delete temp;
return false;
}
};
int main() {
List<int> list;
list.push(1);
list.push(2);
list.push(3);
std::cout << list.pop() << std::endl;
std::cout << list.search(2) << std::endl;
std::cout << list.pop() << std::endl;
return 0;
}
@kamil7108
Copy link

I consider that you have a mistake in a 34 line . Your function don't check the last element in the list.

@EuclideanDreamer
Copy link

I use code like line 34 all the time. Pointer in this case should return nullptr when it goes past the last node, you could say it might be better to use nullptr on line 14, but the compiler will probs fix that anyway.

to OP:
Thanks for the example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment