102 lines
1.8 KiB
C++
102 lines
1.8 KiB
C++
/**~*~*~*
|
|
CIS 22C
|
|
Project: Stack of strings (pop)
|
|
|
|
Written by: Iurii Tatishchev
|
|
IDE: CLion
|
|
*~*/
|
|
#include <iostream>
|
|
#include <string>
|
|
|
|
using namespace std;
|
|
|
|
class Stack_str {
|
|
private:
|
|
// Structure for the stack nodes
|
|
struct StackNode {
|
|
string value; // Value in the node
|
|
StackNode *next; // Pointer to next node
|
|
};
|
|
|
|
StackNode *top; // Pointer to the stack top
|
|
int length;
|
|
|
|
public:
|
|
Stack_str(){ top = NULL; length = 0; } //Constructor
|
|
// ~Stack_str(); // Destructor
|
|
|
|
// Stack operations
|
|
bool isEmpty() {
|
|
return length == 0;
|
|
}
|
|
|
|
bool push(string);
|
|
|
|
string pop();
|
|
|
|
string peek() {
|
|
return top->value;
|
|
}
|
|
|
|
int getLength() {
|
|
return length;
|
|
}
|
|
};
|
|
|
|
/**~*~*~*
|
|
Member function push: pushes the argument onto the stack.
|
|
*~**/
|
|
bool Stack_str::push(string item) {
|
|
StackNode *newNode; // Pointer to a new node
|
|
|
|
// Allocate a new node and store num there.
|
|
newNode = new StackNode;
|
|
if (!newNode)
|
|
return false;
|
|
newNode->value = item;
|
|
|
|
// Update links and counter
|
|
newNode->next = top;
|
|
top = newNode;
|
|
length++;
|
|
|
|
return true;
|
|
}
|
|
|
|
/**~*~*~*
|
|
Member function pop pops the value at the top
|
|
of the stack off, and returns it
|
|
Assume stack is not empty
|
|
*~**/
|
|
string Stack_str::pop() {
|
|
string val = this->top->value;
|
|
|
|
StackNode* oldTop = this->top;
|
|
this->top = this->top->next;
|
|
this->length--;
|
|
delete oldTop;
|
|
|
|
return val;
|
|
}
|
|
|
|
|
|
int main() {
|
|
|
|
Stack_str s;
|
|
string item;
|
|
|
|
getline(cin, item);
|
|
while (item != "0") {
|
|
s.push(item);
|
|
cin.clear();
|
|
getline(cin, item);
|
|
}
|
|
|
|
if (s.isEmpty()) cout << "Empty Stack!\n";
|
|
|
|
while (!s.isEmpty()) {
|
|
cout << s.pop() << "\n";
|
|
}
|
|
|
|
return 0;
|
|
} |