栈
栈是限定仅在表尾进行插入和删除操作的线性表
栈的顺序存储结构
①栈的结构定义:首先是先搞清楚数组那一边作为栈底较好,显然是数组下标为0的作为栈底好,
typedef int Elemtype;
typedef struct {
Elemtype data[MAXSIZE];
int top;
}sqstack;
②进栈操作:只需移动栈顶指针即可,看图
void push(sqstack *s,int X){
if(s->top>=MAXSIZE-1){
printf("ERROR");
}
s->top++;
s->data[s->top]=X;
}
③出栈操作
void pop(sqstack *s,Elemtype *e){
if(s->top==-1){
printf("EOOOR");
}
*e=s->data[s->top];
s->top--;
}
栈的链式存储
①和顺序结构一样,首先确定栈顶的位置,单链表有头指针,栈顶有栈顶指针,所以让他合二为一,即让他作栈顶的位置。
typedef int Elemtype;
typedef struct Link{
Elemtype data;
struct Link *next;
}link;
typedef struct Stack{
link *top;
int count;
}stack;
②进栈操作,由于栈是先进后出,那么要让新节点每次插入的时候都处于链表第一个位置,即使用链表的头插法,
Status push(stack *s,int X){
link *temp=(link*)malloc(sizeof(link));
temp->data=X;
temp->next=s->top;
s->top=temp;
s->count++;
return OK;
}
④出栈操作,也是简单的3句语句
Status pop(stack *s,Elemtype *e){
if(s->top==NULL){
return ERROR;
}
link *temp;
temp=s->top;
*e=temp->data;
s->top=temp->next;
free(temp);
s->count--;
return OK;
}
队列
#include<stdio.h>
#define QueueSize 100
typedef int Elemtype;
typedef struct{
Elemtype data[QueueSize];
int front;
int rear;
}sqqueue;
void ininSqQueue(sqqueue *q){
q->front = 0;
q->rear = 0;
}
void EnSqQueue(sqqueue *q , Elemtype i){
if((q->rear+1)%QueueSize != q->front){
q->data[q->rear] = i;
q->rear = (q->rear + 1)%QueueSize;
}
}
void DeSqQueue(sqqueue *q , Elemtype *e){
if(q->front != q->rear){
*e = q->data[q->front];
q->front = (q->front + 1)%QueueSize;
}
}
int Sqlenth(sqqueue *q){
return (q->rear - q->front + QueueSize)%QueueSize;
}
int main(){
sqqueue *test;
ininSqQueue(test);
for(int i = 1;i<=5;i++){
EnSqQueue(test , i);
}
for(int i = 1;i<=5;i++){
Elemtype num;
DeSqQueue(test , &num);
printf("%d" , num);
}
}