c++ 用switch语句设计一个选择式菜单,编写链式栈进栈、出栈、显示栈中全部元素的程序,将一个正整数n转换成R进制,要求用顺序栈的来实现
时间: 2024-05-10 18:17:36 浏览: 161
基于C++实现的基础数据结构、泛型数据结构及高阶数据结构,含链式栈、顺序栈、单链表、带头双向循环链表、顺序表、泛型数据结构
以下是使用switch语句设计的选择式菜单的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "请选择菜单项:" << endl;
cout << "1. 新建" << endl;
cout << "2. 打开" << endl;
cout << "3. 保存" << endl;
cout << "4. 另存为" << endl;
cout << "5. 退出" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "新建文件" << endl;
break;
case 2:
cout << "打开文件" << endl;
break;
case 3:
cout << "保存文件" << endl;
break;
case 4:
cout << "另存为文件" << endl;
break;
case 5:
cout << "退出程序" << endl;
break;
default:
cout << "无效选择" << endl;
break;
}
return 0;
}
```
下面是链式栈的实现代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
void push(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = head;
head = newNode;
}
void pop() {
if (head == NULL) {
cout << "栈已空" << endl;
return;
}
Node* temp = head;
head = head->next;
delete temp;
}
void display() {
if (head == NULL) {
cout << "栈已空" << endl;
return;
}
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
LinkedList stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.display();
stack.pop();
stack.pop();
stack.display();
return 0;
}
```
下面是将一个正整数n转换成R进制的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n, r;
cout << "请输入一个正整数n和进制r:";
cin >> n >> r;
int stack[100];
int top = -1;
while (n != 0) {
stack[++top] = n % r;
n /= r;
}
while (top != -1) {
cout << stack[top--];
}
cout << endl;
return 0;
}
```
阅读全文