2020-10-07

    科技2024-08-04  29

    C++数据结构

    队列的链式结构的实现与操作

    定义一个链式队列,可以对队列进行“入队”、“出队”、“清空队列”、“获取队首元素”等操作。键盘输入一些命令,可以执行上述操作。本题中,队列的元素为字符。 #include using namespace std; struct Node{ char data; Node* next;

    }; class CirQueue{ public: CirQueue(); void EnQueue(char x); char DeQueue(); char GetHead(); void ClQueue(); private: Node*front,rear; }; CirQueue::CirQueue() { Node s = NULL; s = new Node; s->next = NULL; front = rear = s; }

    void CirQueue::EnQueue(char x) { Node* s = NULL; s = new Node; s->data = x; s->next = NULL; rear->next = s; rear = s; }

    char CirQueue::DeQueue() { if (front == rear) { throw"None"; } Node* p = front->next; char x = p->data; front->next = p->next;

    if (p->next == NULL) { rear = front; } delete p; return x;

    }

    char CirQueue::GetHead() { if (rear == front) { throw"None"; }

    return front->next->data;

    }

    void CirQueue::ClQueue() { Node* s = new Node; s->next = NULL; rear = front = s; }

    int main() { char t; CirQueue S;

    while (1) { cin >> t; if (t == 'E') { cin >> t; S.EnQueue(t); } else if (t == 'D') { try { cout << S.DeQueue() << endl; } catch (const char* str) { cout << str << endl; } } else if (t == 'G') { try { cout << S.GetHead() << endl; } catch (const char* str) { cout << str << endl; } } else if (t == 'C') { S.ClQueue(); } else { break; } }
    Processed: 0.009, SQL: 8