Last active
May 31, 2023 13:04
-
-
Save unreadable/fcf83725fb80a6790a43426940644523 to your computer and use it in GitHub Desktop.
C++ Template List Implementation
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
#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; | |
} |
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
I consider that you have a mistake in a 34 line . Your function don't check the last element in the list.