堆栈
1.先进后出,后进先出
2.只能在一端(栈顶,Top)进行插入(入栈,Push)和删除(出栈,Pop)
堆栈的基本操作
Stack CreateStack(int MaxSize); //生成空堆栈,其最大长度为MaxSize
int IsFull(Stack S, int MaxSize); //判断堆栈S是否已满
viod Push(Stack S, ElementType item); //将元素item压入堆栈S
int IsEmpty(Stack S); //判断堆栈S是否为空
ElementType Pop(Stack S); //删除并返回栈顶元素
堆栈的表示
1.数组
//堆栈的定义
#define MaxSize <存储原始的最大个数>
typedef struct
{
ElementType Data[MaxSize];
int Top;
}Stack;
//入栈Push
void Push(Stack *S, ElementType item)
{
if(S->Top == MaxSize - 1)
{
printf("error")
return;
}
else
{
S->Data[++(S->Top)] = item;
return;
}
}
//出栈Pop
ElementType Pop(Stack *S)
{
if(S->Top == -1)
{
printf("error");
return ERROR;
}
else
return (S->Data[(S->Top)--]);
}
2.单项链表
//堆栈的定义
typedef struct Node
{
ElementType Data;
struct Node *Next;
}LinkStack;
LinkStack *Top;
//创建一个堆栈
LinkStack *CreateStack()
{
LinkStack *S;
S = (LinkStack *)malloc(sizeof(struct Node));
S->Next = NULL;
}
//判断堆栈是否为空
int IsEmpty(LinkStack *S)
{
return (S->Next == NULL);
}
//入栈Push
void Push(ElementType item, LinkStack *S)
{
struct Node *TmpCell;
TmpCell = malloc(sizeof(struct Node));
TmpCell->Element = item;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
//出栈Pop
void Pop(LinkStack *S)
{
struct Node *FirstCell;
ElementType result;
if(IsEmpty(S))
{
printf("error");
return NULL;
}
else
{
FirstCell = S->Next;
S->Next = FirstCell->Next;
result = FirstCell->Element;
free(FirstCell);
return result;
}
}
队列
1.先进先出(FIFO,first-in first-out),后进后出
2.只能在一头插入,另一端删除
队列的基本操作
1.Queue CreateQueue(int MaxSize); //生产长度为MaxSize的空队列
2.int IsFullQ(Queue Q, int MaxSize); //判断队列Q是否已满
3.void AddQ(Queue Q, ElementType item); //将元素插入队列Q中
4.int IsEmptyQ(Queue Q); //判断队列Q是否为空
5.ElementType DeletQ(Queue Q); //将队头元素从队列中删除并返回
队列的表示
1.数组(顺序存储)
#define MaxSize <存储原始的最大个数>
typedef struct
{
ElementType Data[MaxSize];
int rear;
int front;
}Queue;
//入队
void AddQ(Queue *P, ElementType item)
{
if((P->rear+1)%MaxSize == P->front)
{
printf("Full");
return;
}
P->rear = (P->rear + 1)%MaxSize;
P->Data[P->rear] = item;
}
//出队
ElementType DeleteQ(Queue *P)
{
if(P->front == P->rear)
{
printf("Empty");
return ERROR;
}
else
{
P->front = (P->front+1)%MaxSize;
return P->Data[P->front];
}
}
2.链表
typedef struct Node
{
ElementType Data;
struct Node *Next;
}QNode;
typedef struct
{
QNode *rear;
QNode *front;
}LinkQueue;
LinkQueue *P;
//出队
ElementType DeleteQ(LinkQueue *P)
{
QNode *FrontCell;
ElementType FrontElem;
if(P->front == NULL)
{
printf("Empty");
return ERROR;
}
FrontCell = P->front;
if(P->frony == P->rear)
{
P->front = P->rear=NULL;
}
else
{
P->front = P->front->Next;
}
FrontElem = FrontCell->Data;
free(FrontCell);
return FrontElem;
}