栈存入数据,就像把东西往箱子里面放一样,先放进去的最后取出来。
如下图所示:
一个栈需要两个指针标识栈顶与栈底,栈顶以TOP标识,栈底以BOTTOM来标识。
栈底指针永远指向栈底元素。
代码实现:
typedef struct Node
{
int nData;
Node * pNext;
} * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBtm;
} *PSTACK;
void initStack(PSTACK pStack);
void push_Stack(PSTACK pStack, int nValue);
bool isEmpty_Stack(const PSTACK pStack);
void show_Stack(const PSTACK pStack);
void pop_Stack(PSTACK pStack);
int main()
{
Stack oStack;
initStack(&oStack);
push_Stack(&oStack, 1);
push_Stack(&oStack, 2);
push_Stack(&oStack, 3);
push_Stack(&oStack, 4);
push_Stack(&oStack, 5);
pop_Stack(&oStack);
pop_Stack(&oStack);
pop_Stack(&oStack);
show_Stack(&oStack);
}
void initStack(PSTACK pStack)
{
pStack->pBtm = (PNODE)malloc(sizeof(Node));
if (nullptr == pStack->pBtm)
{
std::cout << "内存申请失败!";
exit(-1);
}
pStack->pBtm->pNext = nullptr;
pStack->pTop = (PNODE)malloc(sizeof(Node));
if (nullptr == pStack->pTop)
{
std::cout << "内存申请失败!";
exit(-1);
}
pStack->pTop->pNext = pStack->pBtm;
}
void push_Stack(PSTACK pStack, int nValue)
{
//创建一个新节点
PNODE pNewNode = (PNODE)malloc(sizeof(Node));
if (nullptr == pNewNode)
{
std::cout << "内存申请失败!";
exit(-1);
}
pNewNode->nData = nValue;
PNODE pTempNode = pStack->pTop->pNext;
pNewNode->pNext = pTempNode;
pStack->pTop->pNext = pNewNode;
}
bool isEmpty_Stack(const PSTACK pStack)
{
if (pStack->pTop->pNext == pStack->pBtm)
{
return true;
}
return false;
}
void show_Stack(const PSTACK pStack)
{
if (isEmpty_Stack(pStack))
{
return;
}
PNODE pNode = pStack->pTop->pNext;
while (pNode != pStack->pBtm)
{
std::cout << pNode->nData << "\t";
pNode = pNode->pNext;
}
}
void pop_Stack(PSTACK pStack)
{
if (isEmpty_Stack(pStack))
{
return;
}
PNODE pTempNode = pStack->pTop->pNext;
pStack->pTop->pNext = pTempNode->pNext;
std::cout << "删除的元素为:" << pTempNode->nData << "\n";
free(pTempNode);
}