顺序栈【数据结构】

栈:

栈作为一种数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。栈具有记忆作用,对栈的插入与删除操作中,不需要改变栈底指针 ————百度百科

在实际的应用中我们大多创建的为顺序栈,因为顺序栈在入栈和出栈时的时间复杂度均为O(1)。

顺序栈:

顺序栈构成:

typedef struct Stack{
	SDataType _array[MAX_SIZE];
	int _size;		//栈中有效元素个数
}Stack;
基本操作:

初始化:

void InitStack(Stack *S)
{
	int i = 0;
	assert(S);

	S->_size = 0;
}

入栈:

void PushStack(Stack *S, SDataType data)
{
	assert(S);
	if (S->_size == MAX_SIZE)
	{
		return;
	}
	S->_array[S->_size++] = data;
}

出栈:

void PopStack(Stack *S)
{
	assert(S);
	if (StackEmpty(S))
	{
		return;
	}
	S->_size--;
}

栈顶元素:

SDataType TopStack(Stack *S)
{
	assert(S);
	return S->_array[S->_size-1];
}

栈空判断:

int StackEmpty(Stack* S)
{
	assert(S);
	return 0 == S->_size;
}

栈大小判断:

int SizeStack(Stack *S)
{
	assert(S);
	return S->_size;
}
完整代码:
stack.c

#include "Stack.h"


void InitStack(Stack *S)
{
	int i = 0;
	assert(S);

	S->_size = 0;
}

void PushStack(Stack *S, SDataType data)
{
	assert(S);
	if (S->_size == MAX_SIZE)
	{
		return;
	}
	S->_array[S->_size++] = data;
}

void PopStack(Stack *S)
{
	assert(S);
	if (StackEmpty(S))
	{
		return;
	}
	S->_size--;
}

int FindStack(Stack *S, SDataType data)
{
	int i = 0;
	assert(S);
	for (; i < S->_size; i++)
	{
		if (data == S->_array[i])
			return i;			//返回地址		(0?)
	}
	return -1;
}

int SizeStack(Stack *S)
{
	assert(S);
	return S->_size;
}

int StackEmpty(Stack* S)
{
	assert(S);
	return 0 == S->_size;
}

SDataType TopStack(Stack *S)
{
	assert(S);
	return S->_array[S->_size-1];
}

void StackPrint(Stack *S)
{
	int i = 0;
	assert(S);
	for (;i < S->_size; i++)
	{
		printf("%d--->",S->_array[i]);
	}
	printf("\n");
}


void TestStack()
{
	Stack S;
	int tmp = 0;
	SDataType Top = 0;
	int size = 0;
	InitStack(&S);
	PushStack(&S, 1);
	PushStack(&S, 2);
	PushStack(&S, 3);
	PushStack(&S, 4);
	PushStack(&S, 5);
	PushStack(&S, 6);
	StackPrint(&S);
	PopStack(&S);
	PopStack(&S);
	StackPrint(&S);
	tmp = FindStack(&S, 1);
	if (-1 != tmp)
	{
		printf("find!-----in %d \n", tmp+1);
	}
	else
	{
		printf("not find!\n");
	}
	Top = TopStack(&S);
	printf("Top = %d\n", Top);
	size = SizeStack(&S);
	printf("size = %d\n", size);
}

stack.h

#pragma once 

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef char SDataType;

#define MAX_SIZE 10

typedef struct Stack{
	SDataType _array[MAX_SIZE];
	int _size;
}Stack;


void InitStack(Stack *S);					
void PushStack(Stack *S, SDataType data);		//时间复杂度O(1)
void PopStack(Stack *S);							//O(1)
int FindStack(Stack *S, SDataType data);
int SizeStack(Stack *S);
int StackEmpty(Stack* S);
SDataType TopStack(Stack *S);
void StackPrint(Stack *S);

void TestStack();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值