This is the code:
#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";
getline(cin, Str);
for(i=0; Str[i]!='\0'; i++)
{
c=Str[i];
if('0'<=c && c<='9')
{
St1.push(c);
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(n);
else
flag = false;
}
if(flag)
St2.print();
cin >> a;
return 0;
}
In main, when I enter a String of 2352, it always prints "Your string didn't include any numbers!". So obviously, nothing is being pushed into the stack. This program should reads a String that belongs to this family: {a^p b^p | p>0} based on the stack data structure. p is the power.. so if p > 0 it displays the values of a and b.. So in this case " 2352 " a = 2, p = 3, b = 5, and p =2.. since p > 0.. 2 and 5 should be printed. also, as long as i'm pushing integers only between 0 and 9 into the stack, that means p will never be negative.
Aucun commentaire:
Enregistrer un commentaire