Вот один из способов сделать это с помощью функций create_list, search_up, search_down и destory_list. Я пытаюсь использовать имена переменных, которые являются более описательными. Я не люблю listrec2
, потому что это очень запутанно. Это заставляет меня думать о втором узле, но это не то, чем он является. Это тип узла.
Кроме того, полезно использовать заглавные буквы для ваших типов (например, Node). Затем вы можете использовать строчную версию для объекта (например, узел узла;)
#include <iostream>
using namespace std;
// of linked list in reverse order
// Structure of a Node
template<class T>
struct Node {
T value; //corresponds to data
Node *next; //points to next Node
Node *prev; //points to previous nod
};
template<typename T>
void CreateList(Node<T> *&head, Node<T> *&tail, T value_array[], int array_size)
{
head = nullptr;
tail = nullptr;
for (int i = 0; i < array_size; i++) {
// Create new node and add node to the end of the list
Node<T> *node = new Node<T>();
node->next = nullptr;
node->prev = tail;
if (head == nullptr) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
node->value = value_array[i];
}
}
template<class T>
void downwardSearch(Node<T> *head)
//traverse from start of linked list to end of linked list
//print out value of each Node along way
{
Node<T> *ptr = head;
cout << "The array in forward order: " << endl;
while (ptr != nullptr) {
cout << ptr->value;
ptr = ptr->next;
}
}
template<class T>
void DestroyList(Node<T> *head)
{
Node<T> *ptr;
while (head != nullptr) {
ptr = head->next;
delete head;
head = ptr;
}
}
template<class T>
void upwardSearch(Node<T> *tail)
{
Node<T> *ptr = tail;
cout << "The array in reverse order or backwards: " << endl;
while (ptr != nullptr) {
cout << ptr->value;
ptr = ptr->prev;
}
cout << endl;
}
int main()
{
char s[] = {'c', 'd', 'e'};
Node<char> *head;
Node<char> *tail;
CreateList<char>(head, tail, s, 3);
upwardSearch(tail);
downwardSearch(head);
DestroyList(head);
head = tail = nullptr;
return 0;
}