1.棧的總結
出入棧的順序:先入先出。兩種情況:棧滿,棧空。
操作:push,pop(彈出棧頂元素), peek (訪問棧頂元素)
檢測棧狀態(tài):stackEmpty(檢測棧是否為空),stackFull(檢測棧是否已滿)
stack線性表實現(xiàn)
const int MaxStackSize=50;
class stack
{
private:
DataType Stacklist[MaxStackSize];
int top;
public:
//initilize
stack(void);
void push(const DataType item);
DataType pop();
void clearStack();
DataType seek() const;
int stackEmpty() const;
int stackFull() const;
}
//DataType is predefined with typedef;
stack::stack():top(-1);
stack::push(const DataType item)
{
if(top==Maxtacksize-1)
{
//the stack is full error
//error message;
exit(0);
}
top++;
Stacklist[top]=item;
}
DataType stack::pop()
{
if(top==-1)
{
//the stack is empty
//error message;
exit(0);
}
DateType temp=Stacklist[top];
top--;
return temp;
}
DataType stack:peek() const
{
if(top==-1)
{
//error message
exit(1);
}
return Sacklist[top];
}
int Stack:StackEmpty() const
{
return top==-1;
}
int Stack:StackFull() const
{
return top==MaxStackSize;
}
stack鏈表實現(xiàn)
typedef int elemType;
struct sNode{
elemType data;
struct sNode *next;
};
/* 1).初始化鏈棧為空 */
void initStack(struct sNode* *hs)//初始化
{
*hs = NULL;
return;
}
/* 2).向鏈中插入一個元素(入棧) */
void push(struct sNode* *hs, elemType x)
{
struct sNode *newP;
newP = malloc(sizeof(struct sNode));
if(newP == NULL){
printf("內(nèi)在空間分配失敗! ");
exit(1);
}
newP->data = x; /* 給新分配的結點賦值 */
/* 向棧頂插入新結點 */
newP->next = *hs;
*hs = newP;
return;
}
/* 3).從鏈棧中刪除一個元素并返回它(出棧) */
elemType pop(struct sNode* *hs)
{
struct sNode *p;
elemType temp;
if(*hs == NULL){
printf("棧空無法刪除! ");
exit(1);
}
/* 暫存棧頂結點指針,并使棧頂指針指向下一個結點 */
p = *hs;
*hs = p->next;
/* 暫存原棧頂元素以便返回,同時回收原棧頂結點 */
temp = p->data;
free(p);
return temp; /* 返回原棧頂元素 */
}
/* 4).讀取棧頂元素 */
elemType peek(struct sNode* *hs)
{
/* 對于空棧則退出運行 */
if(*hs == NULL){
printf("棧空,無棧頂元素! ");
exit(1);
}
return (*hs)->data; /* 返回棧頂結點的值 */
}
/* 5).判斷鏈棧是否為空,為空返回1,否則返回0 */
int emptyStack(struct sNode* *hs)
{
if(*hs == NULL){
return 1;
}else{
return 0;
}
}
/* 6).清除鏈棧為空 */
void clearStack(struct sNode* *hs)
{
struct sNode *cp, *np;
cp = *hs; /* 使cp指向棧頂結點 */
/* 從棧底依次刪除每個結點 */
while(cp != NULL){
np = cp->next;
free(cp);
cp = np;
}
*hs = NULL; /* 置鏈棧為空 */
return;
}