链式栈
空栈示意图: 栈中有元素示意图:
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
typedef struct Node{
int data;
struct Node * next;
}NODE, * PNODE;
typedef struct Stack{
PNODE pTop;
PNODE pBottom;
}STACK, * PSTACK;
void init(PSTACK pS){
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (pHead == NULL)
{
printf("内存分配失败!\n");
}
pS->pBottom = pHead;
pS->pTop = pHead;
pS->pTop->next = NULL;
}
void push(PSTACK pS, int val){
PNODE pnew = (PNODE)malloc(sizeof(NODE));
pnew->data = val;
pnew->next = pS->pTop;
pS->pTop = pnew;
return;
}
void traverse(PSTACK pS){
PNODE p = pS->pTop;
while(p != pS->pBottom){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return;
}
bool pop(PSTACK pS, int * p){
if(pS->pBottom == pS->pTop){
return false;
}
*p = pS->pTop->data;
PNODE q = pS->pTop;
pS->pTop = q->next;
free(q);
return true;
}
void clear(PSTACK pS){
if(pS->pBottom == pS->pTop){
return ;
}
PNODE p = pS->pTop;
while(p != pS->pBottom){
PNODE q = p;
p = p->next;
free(q);
}
pS->pTop = pS->pBottom;
return ;
}
int main(){
STACK S;
int val;
init(&S);
push(&S, 1);
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
traverse(&S);
if(pop(&S, &val)){
printf("出栈元素为:%d\n", val);
}else{
printf("出栈失败");
}
traverse(&S);
clear(&S);
printf("将栈清空!\n");
if(pop(&S, &val)){
printf("出栈元素为:%d\n", val);
}else{
printf("出栈失败");
}
return 0;
}
循环队列
空队示意图: 队满判断方法: 牺牲一个元素空间,来区别队空或队满。入队前,先判Q.rear+1是否等于Q.front,若是则为队满。
# include <stdio.h>
# include <malloc.h>
# include <stdbool.h>
#define MAX_SIZE 6
typedef struct Queue
{
int * pBase;
int front;
int rear;
}QUEUE;
void init(QUEUE * pQ){
pQ->pBase = (int *)malloc(sizeof(int) * MAX_SIZE);
pQ->front = 0;
pQ->rear = 0;
}
bool is_full(QUEUE * pQ){
if((pQ->rear + 1) % MAX_SIZE == pQ->front){
printf("该循环队列已满!\n");
return true;
}
return false;
}
bool en_queue(QUEUE * pQ, int val){
if(is_full(pQ)){
printf("队列已满,无法添加元素!\n");
return false;
}else{
pQ->pBase[pQ->rear] = val;
pQ->rear = (pQ->rear + 1) % MAX_SIZE;
return true;
}
}
bool de_queue(QUEUE * pQ, int * val){
if(pQ->front == pQ->rear){
printf("该队列为空,无法出队!\n");
return false;
}else{
*val = pQ->pBase[pQ->front];
pQ->front = (pQ->front + 1) % MAX_SIZE;
return true;
}
}
void traverse_queue(QUEUE * pQ){
int i = pQ->front;
if (pQ->front == pQ->rear)
{
printf("该循环队列为空!\n");
return;
}
while((pQ->rear + MAX_SIZE - i) % MAX_SIZE > 0){
printf("%d ", pQ->pBase[i]);
i++;
}
printf("\n");
}
int main(){
QUEUE Q;
int val;
init(&Q);
en_queue(&Q, 1);
en_queue(&Q, 2);
en_queue(&Q, 3);
if(de_queue(&Q, &val)){
printf("出队伍成功!出队元素为:%d", val);
printf("\n");
}
en_queue(&Q, 4);
en_queue(&Q, 5);
if(de_queue(&Q, &val)){
printf("出队伍成功!出队元素为:%d", val);
printf("\n");
}
en_queue(&Q, 6);
traverse_queue(&Q);
return 0;
}
|