c++用switch语句设计一个选择式菜单,编写链式栈进栈、出栈、显示栈中全部元素,将一个正整数n转换成R进制,要求用顺序栈的来实现。
时间: 2024-05-16 16:16:47 浏览: 96
这是一个比较基础的编程题,下面是代码示例:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Stack {
public:
Stack() {
top = NULL;
}
void push(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = top;
top = newNode;
}
int pop() {
if (top == NULL) {
return -1;
}
Node* temp = top;
int val = top->data;
top = top->next;
delete temp;
return val;
}
void display() {
Node* curr = top;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
private:
Node* top;
};
int main() {
int choice, n, r;
Stack s;
do {
cout << "1. Push element" << endl;
cout << "2. Pop element" << endl;
cout << "3. Display stack" << endl;
cout << "4. Convert to R-base" << endl;
cout << "0. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
int val;
cout << "Enter value to push: ";
cin >> val;
s.push(val);
break;
case 2:
int popVal;
popVal = s.pop();
if (popVal == -1) {
cout << "Stack is empty" << endl;
} else {
cout << "Popped value is: " << popVal << endl;
}
break;
case 3:
s.display();
break;
case 4:
cout << "Enter number to convert: ";
cin >> n;
cout << "Enter base of conversion: ";
cin >> r;
if (r < 2 || r > 16) {
cout << "Invalid base" << endl;
} else {
Stack result;
while (n > 0) {
int rem = n % r;
n /= r;
result.push(rem);
}
cout << "Result: ";
result.display();
}
break;
case 0:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid choice" << endl;
}
} while (choice != 0);
return 0;
}
```
这段代码中,我们通过一个 `Stack` 类来实现链式栈的进栈、出栈和显示栈中全部元素。在主函数中,我们通过一个 `switch` 语句来实现选择式菜单,用户可以通过输入数字来选择相应的操作。其中,第四个选项可以将一个正整数转换成任意进制,我们通过一个新的 `Stack` 对象来存储转换后的结果,并将结果输出到控制台。
阅读全文