1.顺序表实现栈结构 :
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
//#define N 10
//typedef int STDataType;
//typedef struct Stack
//{
// STDataType a[N];
// int top;
//}ST;
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void StackInit(ST* ps);
void StackDestroy(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
STDataType StackTop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
#include "stck.h"
void StackInit(ST* ps)
{
assert(ps);
ps->a=NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a =NULL;
ps->top = ps->capacity=0;
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if(ps->top == ps->capacity)
{
int newCapcity = ps->capacity==0?4:ps->capacity*2;
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newCapcity);
if(tmp==NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapcity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps)
{
return ps->a[ps->top-1];
}
bool StackEmpty(ST* ps)
{
return ps->top==0;
}
int StackSize(ST* ps)
{
return ps->top;
}
2.单链表实现队列
/*
* Copyright (c) 2022.05.23
* All rights reserved.
*
* 摘 要:链表实现队列
* 当前版本:1.1
* 作 者:赵鹏
* 完成日期:2022年5月23日
*/
#pragma once
#include<stdio.h>
#include <assert.h>
#include<stdlib.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
int size;
QNode* head;
QNode* tail;
}Queue;
void QueueInit(Queue* pq);
void QueueDestroy(Queue*pq);
void QueuePush(Queue*pq,QDataType x);
void QueuePop(Queue* pq);
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue*pq);
int QueueSize(Queue* pq);
#include "Queue.h"
void QueueInit(Queue* pq)
{
pq->head =pq->tail=NULL;
pq->size=0;
}
void QueueDestroy(Queue*pq)
{
QNode* cur = pq->head;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur=next;
}
}
void QueuePush(Queue*pq,QDataType x)
{
QNode* newNode = (QNode*)malloc(sizeof(QNode));
newNode->data = x;
newNode->next=NULL;
if(pq->tail==NULL)
{
pq->head =pq->tail=newNode;
}else
{
pq->tail->next = newNode;
pq->tail = newNode;
}
pq->size++;
}
void QueuePop(Queue* pq)
{
if(pq->head->next==NULL)
{
free(pq->head);
}else{
QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
pq->size--;
}
QDataType QueueFront(Queue* pq)
{
return pq->head->data;
}
QDataType QueueBack(Queue* pq)
{
return pq->tail->data;
}
bool QueueEmpty(Queue*pq)
{
return pq->head==NULL;
}
int QueueSize(Queue* pq)
{
return pq->size;
}