如何解决用 C++ 模拟一个基本的电梯
所以我最近了解了双向链表如何前进和后退,并且我有了尝试模拟电梯如何上下移动的想法。我写了这段代码,并且没有错误地构建了它。当我运行它时,它卡在了输入你的目的地:
这是我的预期输出:
这是一个电梯模拟器
输入要建造电梯的楼层数:
已创建以下楼层:
1,2,3,4,5,6,7,8,9,10,
输入目的地:
电梯正在上升.....
电梯现在在楼层.....2
电梯现在在楼层.....3
电梯现在在楼层.....4
电梯现在在楼层.....5
输入您的目的地:
电梯要下降了.....
电梯现在在楼层.....4
电梯现在在楼层.....3
电梯现在在楼层.....2
电梯现在在楼层.....1
电梯目前在 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。