Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Created January 24, 2022 13:15
Show Gist options
  • Save piusayowale/39cef8801c2274bdc180c9b7c5087451 to your computer and use it in GitHub Desktop.
Save piusayowale/39cef8801c2274bdc180c9b7c5087451 to your computer and use it in GitHub Desktop.
doubly linked list
struct Node {
int value;
Node* next;
Node* prev;
};
static Node* head = nullptr;
static Node* tail = nullptr;
Node* insert(Node*& list, int value) {
Node* temp;
Node* ptr = list;
if (ptr == nullptr) {
temp = new Node;
temp->next = nullptr;
temp->value = value;
temp->prev = nullptr;
list = temp;
head = list;
tail = list;
return list;
}
while (ptr->next != nullptr)
{
ptr = ptr->next;
}
temp = new Node;
temp->prev = ptr;
temp->next = nullptr;
temp->value = value;
ptr->next = temp;
tail = temp;
return list;
}
void transverseForward(Node* list) {
while (list != nullptr)
{
std::cout << list->value << " ";
list = list->next;
}
std::cout << "\n";
}
void transverseBackward() {
Node* list = tail;
while (list != nullptr)
{
std::cout << list->value << " ";
list = list->prev;
}
std::cout << "\n";
}
int main() {
Node* list = nullptr;
list = insert(list, 7);
list = insert(list, 8);
list = insert(list, 0);
list = insert(list, 2);
list = insert(list, 6);
transverseBackward();
transverseForward(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment