栈 源代码:
使用数组实现栈的 出栈、入栈、返回栈顶元素、取得栈的大小、及栈的复制
最重要的是定义结构体,结构体内部两个属性,一个 int 型数组,一个 top 表示数组内的有效数据为 top 个。
#include <stdio.h>
#include <assert.h>
#include <String.h>
typedef int DateType;
#define MAX_SIZE (100)
typedef struct Stack{
DateType array[MAX_SIZE];
int top;
}Stack;
void StackInit(Stack *ps){
assert(ps != NULL);
ps->top = 0;
}
void StackPush(Stack *ps, int key){
assert(ps);
assert(ps->top < MAX_SIZE);
ps->array[ps->top++] = key;
}
void StackPop(Stack *ps){
assert(ps);
assert(ps->top>0);
ps->top--;
}
int StackTop(Stack *ps){
assert(ps);
assert(ps->top > 0);
return ps->array[ps->top-1];
}
int StackSize(Stack *ps){
assert(ps);
return ps->top;
}
void StackCopy(Stack *dest, Stack *src){
assert(src);
dest->top = src->top;
memcpy(dest->array, src->array, (src->top)*sizeof(int));
}
void print(Stack *ps){
for (int i = 0; i < ps->top; i++){
printf("%d ", ps->array[i]);
}
printf("\n");
}
void Test(){
Stack stack;
StackInit(&stack);
StackPush(&stack, 2);
StackPush(&stack, 3);
StackPop(&stack);
print(&stack);
Stack ps;
StackInit(&ps);
StackCopy(&ps, &stack);
print(&ps);
}
队列:
第一步需要定义好结构体:
typedef int DataType; 用DataType 来表示 int 类型
typedef struct QNode{
DataType data; //存放节点数据
struct QNode *pNext; //存放下一个节点的地址
}
typedef struct Queue{
QNode *pFirst; // 第一个节点地址
QNode *pRear; // 最后一个节点地址
int size;//队列中的节点个数即数据个数
}
在此基础上,实现队列的,初始化,插入,删除,取得队列中第一个数据,取得队列长度,判断队列是否为空。
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef int DataType;
//定义节点结构体
typedef struct QNode{
DataType data;
struct QNode *pNext;
}QNode;
//定义队列结构体
typedef struct Queue{
QNode *pFirst;
QNode *pRear;
int size;
}Queue;
//队列初始化
void QueueInit(Queue *ps){
assert(ps != NULL);
ps->pFirst = ps->pRear = NULL;
ps->size = 0;
}
//队列插入
void QueueInsert(Queue *ps, int key){
assert(ps != NULL);
QNode *pNewNode = (QNode *)malloc(sizeof(QNode));
pNewNode->data = key;
pNewNode->pNext = NULL;
//如果此时队列中没有数据
if (ps->size == 0){
ps->pFirst = ps->pRear = pNewNode;
ps->size++;
return;
}
ps->pRear->pNext = pNewNode;
ps->pRear = pNewNode;
ps->size++;
}
//队列删除
void QueuePop(Queue *ps){
assert(ps != NULL);
assert(ps->size > 0);
QNode *OldFirst = ps->pFirst;
ps->pFirst = ps->pFirst->pNext;
ps->size--;
free(OldFirst);
if (ps->pFirst==NULL){
ps->pRear = NULL;
}
}
//队列中的第一个元素
int QueueFront(Queue *ps){
assert(ps != NULL);
assert(ps->size > 0);
return ps->pFirst->data;
}
//1 表示空
//0 表示不空
int QueueIsImpty(Queue *ps){
assert(ps != NULL);
return ps->size == 0 ? 1 : 0;
}
int QueueSize(Queue *ps){
assert(ps != NULL);
return ps->size;
}
void Test(){
Queue ps;
QueueInit(&ps);
QueueInsert(&ps, 2);
QueueInsert(&ps, 3);
QueueInsert(&ps, 5);
QueueInsert(&ps, 9);
QueueInsert(&ps, 7);
QueuePop(&ps);
int size=QueueFront(&ps);
int ISImpty = QueueIsImpty(&ps);
int top = QueueSize(&ps);
printf("%d ", size);
printf("%d ", ISImpty);
printf("%d", top);
}