So I recently learned of Doubly Linked List on how it can go forward as well as backward, and I had this idea of trying to simulate an elevator on how it can move up and down. I wrote this code and I had it built with no errors. When I ran it, it got stuck on Input your destination:
This is my expected output:
This is an Elevator Simulator
Input a number of floors to construct for the elevator:
The following floors have been created:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Input your destination:
The elevator is going up.....
Elevator is now at Floor.....2
Elevator is now at Floor.....3
Elevator is now at Floor.....4
Elevator is now at Floor.....5
Input your destination:
The elevator is going down.....
Elevator is now at Floor.....4
Elevator is now at Floor.....3
Elevator is now at Floor.....2
Elevator is now at Floor.....1
The elevator is currently at floor 1
#include <bits/stdc++.h>
using namespace std;
//using a Doubly Linked List
struct node {
int data;
node *next;
node *prev;
};
node *head = NULL;
node *last = NULL;
node *current = NULL;
void constructNode(node *head, int totalNodes) {
for(int i = 1; i <= totalNodes; i++){
node *newNode = new node;
last = head;
newNode->data = i;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
head = newNode;
return;
}
while (last->next != NULL){
last = last->next;
}
last->next = newNode;
newNode->prev = last;
}
current = head;
return;
}
void locateCurrent(node *current){
cout << "The elevator is currently at floor " << current->data << endl;
}
void moveElevator(int destination){
if(current->data <= destination && destination <= last->data){
cout << "The elevator is going up....." << endl;
while(current->data < destination){
current = current->next;
cout << "Elevator is now at Floor....." << current->data << endl;
}
cout << "You have arrived at your destination." << endl;
}
else if(current->data >= destination && destination >= head->data){
cout << "The elevator is going down....." << endl;
while(current->data > destination){
current = current->prev;
cout << "Elevator is now at Floor....." << current->data << endl;
}
current = current->prev;
cout << "You have arrived at your destination." << endl;
}
}
void displayNodes(node *head){
node *temp = head;
while (temp != NULL){
cout << temp->data << ", ";
temp = temp->next;
}
}
int main() {
cout << "This is an Elevator Simulator " << endl;
cout << "Input a number of floors to construct for the elevator: " << endl;
constructNode(head, 10);
cout << "The following floors have been created: " << endl;
displayNodes(head);
cout << "Input your destination: " << endl;
moveElevator(5);
cout << "Input your destination: " << endl;
moveElevator(1);
//I might need this function in the future but it also is not working right now
locateCurrent(current);
return 0;
}