Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@kamil7108 kamil7108 commented Mar 3, 2020

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

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