栈的插入和删除只在栈顶进行操作,在单链表中,头指针是单链表的必须元素;而在栈中,栈顶指针也是链栈的必须元素,且一般将栈顶放在单链表的头部。
线性表有顺序存储结构和链式存储结构,栈属于线性表的一种,也具有顺序存储结构和链式存储结构。对于栈的链式存储结构,一般称之为链栈。
栈的特点:先进后出
栈函数实现:
1.初始化
2.判满
3.压栈
4.判空
5.出栈
6.带元素出栈
7.清栈
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
typedef int ELEM_TYPE;
typedef struct Stack
{
ELEM_TYPE data[MAXSIZE];
int top;
}Stack;
//pst没有判断NULL情况
void Init(Stack* pst)
{
pst->top = 0;
}
bool IsFull(Stack* pst)
{
return pst->top == MAXSIZE;
}
bool Push(Stack* pst,ELEM_TYPE val)
{
bool rt = false;
if (!IsFull(pst))
{
pst->data[pst->top++] = val;
rt = true;
}
return rt;
}
bool IsEmpty(Stack* pst)
{
return pst->top == 0;
}
bool Pop(Stack* pst)
{
bool rt = false;
if (!IsEmpty(pst))
{
pst->top--;
rt = true;
}
return rt;
}
//带出元素
//bool Pop(Stack* pst, ELEM_TYPE* prt)
//{
// if (IsEmpty(pst))
// {
// return false;
// }
// *prt = pst->data[pst->top - 1];
// pst->top--;
// return true;
//}
ELEM_TYPE Top(Stack* pst)
{
if (IsEmpty(pst))
{
throw exception("stack is empty!");
}
return pst->data[pst->top - 1];
}
void Clear(Stack* pst)
{
pst->top = 0;
}
void Destroyed(Stack* pst)
{
Clear(pst);
}
链栈函数实现:
1.初始化
2.压栈
3.判空
4.出栈
5.带元素出栈
6.清栈
#include<stdio.h>
#include<stdlib.h>
typedef int ELEM_TYPE;
typedef struct Node
{
ELEM_TYPE mdata;
struct Node* pnext;
}Node;
typedef struct Stack
{
Node head;
}Stack;
void Init(Stack* pst)
{
(pst->head).pnext = NULL;
}
Node* BuyNode(ELEM_TYPE val)
{
// Node* pnewnode = (Node*)malloc(sizeof(Node));
Node* pnewnode = new Node();
if (pnewnode != NULL)
{
pnewnode->pnext = NULL;
pnewnode->mdata = val;
}
return pnewnode;
}
bool Push(Stack* pst, ELEM_TYPE val)
{
Node* pnewnode = BuyNode(val);
if (pnewnode == NULL)
{
return false;
}
pnewnode->pnext = (pst->head).pnext;
(pst->head).pnext = pnewnode;
return true;
}
bool IsEmpty(Stack* pst)
{
return (pst->head).pnext == NULL;
}
//不带出元素
bool Pop(Stack* pst)
{
if (IsEmpty(pst))
{
return false;
}
Node* pCur = (pst->head).pnext;
(pst->head).pnext = pCur->pnext;
free(pCur);
return true;
}
//带出元素
bool Pop(Stack* pst, ELEM_TYPE* prt)
{
if (IsEmpty(pst))
{
return false;
}
Node* pCur = (pst->head).pnext;
(pst->head).pnext = pCur->pnext;
*prt = pCur->mdata;
free(pCur);
return true;
}
ELEM_TYPE Top(Stack* pst)
{
if (IsEmpty(pst))
{
throw exception("Stack is Empty!");
}
return ((pst->head).pnext)->mdata;
}
void Clear(Stack* pst)
{
Node* pCur = (pst->head).pnext;
Node* pNext = pCur;
while (pCur != NULL)
{
pNext = pCur->pnext;
free(pCur);
pCur = pNext;
}
(pst->head).pnext = NULL;
}
void Destroyed(Stack* pst)
{
Clear(pst);
}