Last active
May 26, 2024 13:28
-
-
Save rexim/8078996 to your computer and use it in GitHub Desktop.
The answer to the question on stackoverflow: http://stackoverflow.com/questions/20721594/how-to-extract-a-list-from-a-linked-list-in-c/
This file contains hidden or 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> | |
#include <string> | |
using namespace std; | |
template <typename T> | |
struct Node | |
{ | |
T data; | |
Node* next; | |
}; | |
template <typename T> | |
void showList(const Node<T>* head) | |
{ | |
while(head != NULL) | |
{ | |
cout << head->data << " "; | |
head = head->next; | |
} | |
cout << endl; | |
} | |
template <typename T> | |
void pushToList(Node<T>*& head, const T &element) | |
{ | |
Node<T> *p = new Node<T>; | |
p->data = element; | |
p->next = head; | |
head = p; | |
} | |
template <typename T> | |
T popFromList(Node<T>*& head) | |
{ | |
T value; | |
if (head != NULL) { | |
Node<T>* tmp = head; | |
value = head->data; | |
head = head->next; | |
delete tmp; | |
} | |
return value; | |
} | |
template <typename T> | |
Node<T>* arrayToList(const T tab[], size_t size) | |
{ | |
Node<T>* head = NULL; | |
for(int i = size - 1; i >= 0; i--){ | |
pushToList(head, tab[i]); | |
} | |
return head; | |
} | |
template <typename T> | |
void reverseList(Node<T>*& head) | |
{ | |
Node<T> *result = NULL; | |
while(head != NULL) { | |
pushToList(result, popFromList(head)); | |
} | |
head = result; | |
} | |
template<typename T> | |
Node<T>* extract(Node<T>*& head, bool (*predicate)(const T&)) | |
{ | |
Node<T> *extracted = NULL; | |
Node<T> *rest = NULL; | |
while (head != NULL) { | |
T value = popFromList(head); | |
if (predicate(value)) { | |
pushToList(extracted, value); | |
} else { | |
pushToList(rest, value); | |
} | |
} | |
reverseList(extracted); | |
reverseList(rest); | |
head = rest; | |
return extracted; | |
} | |
template <typename T> | |
void deleteList(Node<T>*& head) | |
{ | |
while (head != NULL) { | |
popFromList(head); | |
} | |
} | |
bool isEven(const int& n) | |
{ | |
return n%2 == 0; | |
} | |
bool isLong(const string& s) | |
{ | |
return s.size() >=5; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int xs[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; | |
Node<int> *list = arrayToList(xs, sizeof(xs) / sizeof(xs[0])); | |
Node<int> *extracted = extract(list, &isEven); | |
showList(extracted); | |
showList(list); | |
deleteList(list); | |
deleteList(extracted); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment