@@ -63,52 +63,69 @@ to print the elements of the list in forward and backward order, respectively.
63
63
64
64
#include < iostream>
65
65
using namespace std ;
66
- class Node {
67
- public:
66
+
67
+ // Define a Node class
68
+ class Node {
69
+ public:
68
70
int data;
69
71
Node* next;
70
72
Node* prev;
71
- Node (int d){
73
+ Node (int d) {
72
74
this ->data = d;
73
75
next = NULL ;
74
76
prev = NULL ;
75
77
}
76
78
};
77
- void PrintForward (Node* head){
79
+
80
+ // Function to print the linked list forward
81
+ void PrintForward (Node* head) {
78
82
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 ;
82
86
}
83
87
}
84
- void PrintBackward (Node* tail){
88
+
89
+ // Function to print the linked list backward
90
+ void PrintBackward (Node* tail) {
85
91
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 ;
89
95
}
90
96
}
91
- int main (){
97
+
98
+ int main () {
92
99
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 ) {
100
111
head = newNode;
101
112
tail = newNode;
102
- }else {
113
+ } else {
114
+ // Add the new node to the end of the list
103
115
newNode->next = nullptr ;
104
116
newNode->prev = tail;
105
117
tail->next = newNode;
106
118
tail = newNode;
107
119
}
108
120
}
109
- cout<<" Printing forwardly................................" <<endl;
121
+
122
+ // Print the linked list forward
123
+ cout << " Printing forwardly................................" << endl;
110
124
PrintForward (head);
111
- cout<<" Printing backwardly................................" <<endl;
125
+
126
+ // Print the linked list backward
127
+ cout << " Printing backwardly................................" << endl;
112
128
PrintBackward (tail);
129
+
113
130
return 0 ;
114
- }
131
+ }
0 commit comments