Created
October 4, 2016 13:36
-
-
Save YaoC/f497d1f6800ffc508cb58458865966ec to your computer and use it in GitHub Desktop.
实现一个简单的字符栈
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define STACK_CAPACITY 1000 | |
class Stack { | |
private: | |
char* array; | |
int pos; | |
public: | |
Stack(); // constructor for a stack | |
void push( char c ); // adds c to the top of the stack | |
char pop(); // removes top element, returns it | |
char top(); // returns the top element, w/o removing | |
bool isEmpty(); // returns true iff the stack is empty | |
bool isFull(); // returns true iff the stack is full | |
~Stack(); // destructor for a stack | |
}; | |
Stack::Stack() { | |
pos=0; | |
array = new char[STACK_CAPACITY]; | |
} | |
void Stack::push(char c) { | |
if(!isFull()){ | |
array[pos++] = c;//将c插入到pos位置,pos自增1 | |
} | |
} | |
char Stack::pop() { | |
if(!isEmpty()){ | |
return array[--pos];//top自减1,返回top位置的值 | |
} | |
} | |
char Stack::top() { | |
if(!isEmpty()) | |
return array[pos-1];//top指向下一个值的位置,故应该减1; | |
} | |
bool Stack::isEmpty() { | |
return !(bool)pos; | |
} | |
bool Stack::isFull() { | |
return pos>=STACK_CAPACITY; | |
} | |
Stack::~Stack() { | |
pos=0; | |
delete array; | |
array = NULL; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment