用 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 (将#修改为@)