@@ -63,52 +63,69 @@ to print the elements of the list in forward and backward order, respectively.
6363
6464#include < iostream>
6565using namespace std ;
66- class Node {
67- public:
66+
67+ // Define a Node class
68+ class Node {
69+ public:
6870 int data;
6971 Node* next;
7072 Node* prev;
71- Node (int d){
73+ Node (int d) {
7274 this ->data = d;
7375 next = NULL ;
7476 prev = NULL ;
7577 }
7678};
77- void PrintForward (Node* head){
79+
80+ // Function to print the linked list forward
81+ void PrintForward (Node* head) {
7882 Node* traverse = head;
79- while (traverse!= NULL ){
80- cout<< traverse->data << endl;
81- traverse= traverse->next ;
83+ while (traverse != NULL ) {
84+ cout << traverse->data << endl;
85+ traverse = traverse->next ;
8286 }
8387}
84- void PrintBackward (Node* tail){
88+
89+ // Function to print the linked list backward
90+ void PrintBackward (Node* tail) {
8591 Node* traverse = tail;
86- while (tail!= NULL ){
87- cout<< traverse->data << endl;
88- traverse= traverse->prev ;
92+ while (tail != NULL ) {
93+ cout << traverse->data << endl;
94+ traverse = traverse->prev ;
8995 }
9096}
91- int main (){
97+
98+ int main () {
9299 int n, value;
93- cin>>n;
94- Node *head = nullptr ;
95- Node *tail = nullptr ;
96- for (int i=0 ; i<n; i++){
97- cin>>value;
98- Node *newNode = new Node (value);
99- if (head == NULL ){
100+ cin>>n; // Read the number of nodes to be created
101+ Node *head = nullptr ; // Initialize head pointer
102+ Node *tail = nullptr ; // Initialize tail pointer
103+
104+ // Read 'n' values and create a doubly linked list
105+ for (int i = 0 ; i < n; i++) {
106+ cin >> value; // Read the value for the current node
107+ Node* newNode = new Node (value); // Create a new node with the value
108+
109+ // If the list is empty, set the head and tail to the new node
110+ if (head == NULL ) {
100111 head = newNode;
101112 tail = newNode;
102- }else {
113+ } else {
114+ // Add the new node to the end of the list
103115 newNode->next = nullptr ;
104116 newNode->prev = tail;
105117 tail->next = newNode;
106118 tail = newNode;
107119 }
108120 }
109- cout<<" Printing forwardly................................" <<endl;
121+
122+ // Print the linked list forward
123+ cout << " Printing forwardly................................" << endl;
110124 PrintForward (head);
111- cout<<" Printing backwardly................................" <<endl;
125+
126+ // Print the linked list backward
127+ cout << " Printing backwardly................................" << endl;
112128 PrintBackward (tail);
129+
113130 return 0 ;
114- }
131+ }
0 commit comments