C++ 正在读取属于此族的字符串:{a^p b^p | p>0},基于堆栈数据结构
代码如下:C++ 正在读取属于此族的字符串:{a^p b^p | p>0},基于堆栈数据结构,c++,string,data-structures,stack,C++,String,Data Structures,Stack,代码如下: #include <iostream> #include <string> using namespace std; class Node { public: int data; Node* next; public: Node(int d) { data=d; next=NULL; }; }; c
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
public: Node(int d) {
data=d;
next=NULL;
};
};
class Stack {
Node *head;
public: Stack() {
head = NULL;
};
~Stack(){
while (head) {
Node * temp = head;
head = head->next;
delete temp;
}
}
void push(int data);
int pop();
bool isEmpty();
void print();
};
void Stack::push(int data) {
Node * temp = new Node(data);
temp->next=head;
head=temp;
}
int Stack::pop() {
if(head!=NULL){
int x=head->data;
Node * temp = head;
head=head->next;
delete temp;
return x;
} else {
cout << "The stack is empty!";
return -1;
}
}
bool Stack::isEmpty() {
return head==NULL;
}
void Stack::print() {
Node * temp = head;
while(temp!=NULL){
cout << temp->data << " ";
temp=temp->next;
}
}
int main() {
Stack St1, St2;
char c;
string Str;
int i, a, length = 0;
int n, p;
bool flag = true;
cout << "Enter the String, use this form: np (n is the number and p is the power)\n";
cout << "Press the Enter key when you're done.\n";
getline(cin, Str);
for(i=0; Str[i]!='\0'; i++) {
c=Str[i];
if(c == ' ')
continue;
if(c=='-'&&Str[i+1]!='\0')
{
i++;
c=Str[i];
a=((int)c - '0') * -1;
St1.push(a);
length++;
}
else{
a=(int)c - '0';
St1.push(a);
length++;
}
}
if(length%2 != 0)
a = St1.pop(); /* To make sure the String that was entered has an even length (i.e. a number and its power) */
if(length == 0)
cout << "Your string didn't include any numbers!\n";
while(!St1.isEmpty() && flag)
{
p = St1.pop();
n = St1.pop();
if(p > 0)
St2.push( (int)n );
else
flag = false;
}
if(flag)
St2.print();
else
cout << "Your string doesn't belong to the family; {a^n b^n | n>0}";
cin >> a;
return 0;
}
此程序应根据堆栈数据结构读取属于以下族的字符串:{a^p b^p | p>0}。p是力量。。因此,如果p>0,则显示a和b的值。。在这种情况下,2352a=2,p=3,b=5,p=2。。因为p>0。。2和5应该打印。您的堆栈效率不高。一个std::vector将使用更少的内存分配。您的设计似乎有很多不必要的限制。您确定只允许范围[0;9]中的数字吗?为什么不为power语法引入适当的语义?我建议您假设字符串的格式为a^b,并使用^character作为拆分位置。然后a和b可以有任何整数值。此外,您的堆栈还可以得到改进。如果你真的需要这样做-很好,但是std::vector或std::stack加上漂亮的内存池会更好,也就是更快。我不明白这个错误。当我运行它并输入2352作为输入时,它输出50 53。@username\u是的,这些是2和5的ASCII码。。如何将它们转换为普通整数?我编辑了代码,忘了编辑段落..在Stack::print函数中打印时,只需将它们转换为字符即可。