一、栈:限定仅在表尾进行插入或删除操作的线性表
(1)结构定义
1.1)顺序栈的结构图定义
<img src="https://img-blog.csdn.net/20150313130623819?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZmVpMjAxMjExMDY=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
typedef struct{
int data[maxsize];
int top;
}sqtack;
1.2)顺序栈的基本操作:
先存取,后移动指针
int stack[maxsize]; int top=-1;//初始化声明,<span style="font-size:18px;color:#ff0000;">注意,该方法会导致top指针指向第一个栈顶节点,而不是头结点</span>
stack[++top]=x;//进栈
x=stack[top--];//出栈
stack.top==1;//验证空栈
stack.top==maxize-1;//验证满栈
2.1)链栈的结构定义 注意:该图中没有表示头结点
typedef struct{
int data;
Lnode * next;
}LNode;
2.2)链栈的基本操作
入栈: lst-next=p->next; lst->netx=p;
出栈:
x=lst->next;
p=lst->next;
lst->next=p->next;
free(p);
二、队列 :表尾入,表头出
(1)顺序队列
![](https://img-my.csdn.net/uploads/201205/04/1336120879_1826.png)
- /*队列的数据抽象*/
- typedef struct
- {
- int data[maxsize] ;
- int front;//队列头指针
- int rear;//队列尾指针
- } SqQueue;
- /*判断队列是否为空*/
- bool IsEmpty(SqQueue Q)
- {
- return Q.front==Q.rear;
- }
- /*判断队列是否已满,这里我们牺牲一个空间,为甚么?你懂的*/
- bool IsFull(SqQueue Q)
- {
- return ((Q.rear+1)%MAXQSIZE)==Q.front;
- }
- /*获取队列长度*/
- int QueueLength(SqQueue Q)
- {
- return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
- }
- /*入队列*/
- status InQueue(SqQueue &Q,QElementType e)
- {
- //判断队列是否已满
- if(IsFull(Q))
- return _ERROR;
- Q.base[Q.rear]=e;
- Q.rear = (Q.rear+1)%MAXQSIZE;
- return _OK;
- }
- /*出队列*/
- status OutQueue(SqQueue &Q,QElementType &e)
- {
- /*判断队列是否为空*/
- if(IsEmpty(Q))
- return _ERROR;
- e = Q.base[Q.front];
- Q.front = (Q.front + 1)%MAXQSIZE;
- return _OK;
- }
(2)链队列
- struct Node
- {
- T data;
- Node<T> *next; //此处<T>也可以省略
- };
- struct Queue
- {
- Node *rear;
- Node *front;
- };
进队
- Q->rear->next=s; //将结点s插入到队尾 ,Q为头结点,也就是头指针
- Q->rear=s;
- if (rear==front) throw "下溢";
- p=front->next;
- x=p->data; //暂存队头元素
- front->next=p->next; //将队头元素所在结点摘链
- if (p->next==NULL) rear=front; //判断出队前队列长度是否为1