Created
January 24, 2022 13:15
-
-
Save piusayowale/39cef8801c2274bdc180c9b7c5087451 to your computer and use it in GitHub Desktop.
doubly linked list
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
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