From 57d09b03c6ae5fa72e6e58598466213419ba208d Mon Sep 17 00:00:00 2001 From: danildenha <135840453+danildenha@users.noreply.github.com> Date: Thu, 7 Dec 2023 08:29:54 -0600 Subject: [PATCH] Update Doubly_linked_list.cpp --- data structures/cpp/Doubly_linked_list.cpp | 44 ++++++++++------------ 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/data structures/cpp/Doubly_linked_list.cpp b/data structures/cpp/Doubly_linked_list.cpp index 410141d..85c3177 100644 --- a/data structures/cpp/Doubly_linked_list.cpp +++ b/data structures/cpp/Doubly_linked_list.cpp @@ -8,24 +8,22 @@ class node int data; struct node *prev; struct node *next; + node(int d1, node* p = nullptr, node* n = nullptr) : + data(d1), + prev(p), + next(n) {} }; //functionto create ll struct node *create_dll(struct node *head) { - struct node *newnode = new struct node; - newnode->next = NULL; - newnode->prev = NULL; - cin >> newnode->data; - tail = newnode; - if (head == NULL) - { + int input; + cin >> input; + struct node *newnode = new struct node(input); + if (head == nullptr) { return newnode; - } - else - { - struct node *p = head; - while (p->next != NULL) - { + } else { + node *p = head; + while (p->next != nullptr) { p = p->next; } newnode->prev = p; @@ -36,21 +34,19 @@ struct node *create_dll(struct node *head) //function to insert node at head struct node *insert_at_beg_in_dll(struct node *head) { - struct node *newnode = new struct node; - newnode->next = NULL; - newnode->prev = NULL; - cin >> newnode->data; - if (head == NULL) - { + int input_data; + cin >> input_data; + + // Creating a new node with input data using the constructor + node *newnode = new node(input_data); + + if (head == nullptr) { return newnode; - } - else - { + } else { head->prev = newnode; newnode->next = head; head = newnode; return head; - } } //function to to insert element at end struct node *insert_at_end_in_dll(struct node *head) @@ -140,4 +136,4 @@ int main() cin >> t; } return 0; -} \ No newline at end of file +}