栈(Stack)

首先它是一个线性表,也就是说,栈元素具有线性关系,即前驱后继关系。只不过它是一种特殊的线性表而已。定义中说是在线性表的表尾进行插入和删除操作,这里表尾是指栈顶,而不是栈底。

LinkStack.h

#ifndef LINKSTACK_H
#define LINKSTACK_H

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

#define STACK_FALSE 0
#define STACK_TRUE 1

//链栈结点
typedef struct _LINKNODE{
	void* data;
	struct _LINKNODE* next;
}LinkNode;
//头结点
typedef struct _LINKSTACK{
	LinkNode* head;
	int length;
}LinkStack;

//初始化链栈
LinkStack* InitLinkStack();
//销毁链栈
void DestroyLinkStack(LinkStack* lstack);
//获得栈顶元素
void* TopLinkStack(LinkStack* lstack);
//弹出栈顶元素
void PopLinkStack(LinkStack* lstack);
//获得栈元素个数
int GetLengthLinkStack(LinkStack* lstack);
//向栈中加入元素
int PushLinkStack(LinkStack* lstack,void* data);
//判断栈是否为空
int IsEmptyLinkStack(LinkStack* lstack);

#endif

LinkStack.c

#include"LinkStack.h"

//初始化链栈
LinkStack* InitLinkStack(){

	LinkStack* lstack = (LinkStack*)malloc(sizeof(LinkStack));
	if (lstack == NULL){
		return NULL;
	}
	//初始化
	lstack->head = NULL;
	lstack->length = 0;

	return lstack;
}
//销毁链栈
void DestroyLinkStack(LinkStack* lstack){
	
	while (!IsEmptyLinkStack(lstack)){
		PopLinkStack(lstack);
	}
	free(lstack);
}
//获得栈顶元素
void* TopLinkStack(LinkStack* lstack){
	return lstack->head->data;
}
//弹出栈顶元素
void PopLinkStack(LinkStack* lstack){
	if (lstack->length == 0){
		return;
	}
	//缓存要删除的结点
	LinkNode* pDel =  lstack->head;
	//将被删除结点的下一个结点作为head结点
	lstack->head = pDel->next;
	//释放被删除结点内存
	free(pDel);
	//结点数量减1
	lstack->length--;
}
//获得栈元素个数
int GetLengthLinkStack(LinkStack* lstack){
	return lstack->length;
}
//向栈中加入元素
int PushLinkStack(LinkStack* lstack, void* data){

	//创建结点
	LinkNode* newnode = (LinkNode*)malloc(sizeof(LinkNode));
	newnode->data = data;
	newnode->next = NULL;

	//是否第一次插入元素
	if (lstack->head == NULL){
		lstack->head = newnode;
		lstack->length++;
		return 0;
	}

	//其他插入情况
	newnode->next = lstack->head;
	lstack->head = newnode;
	lstack->length++;

	return 0;
}
//判断栈是否为空
int IsEmptyLinkStack(LinkStack* lstack){
	if (lstack->length == 0){
		return STACK_TRUE;
	}
	return STACK_FALSE;
}

main.c

#include"LinkStack.h"

typedef struct _TEAHCER{
	char name[64];
	int age;
}Teacher;

void test01(){
	
	//创建链栈
	LinkStack* lstack = InitLinkStack();
	//创建数据
	Teacher t1, t2, t3;
	t1.age = 10;
	t2.age = 20;
	t3.age = 30;
	strcpy(t1.name, "aaa");
	strcpy(t2.name, "bbb");
	strcpy(t3.name, "ccc");
	//向栈中添加元素
	PushLinkStack(lstack, &t1);
	PushLinkStack(lstack, &t3);
	PushLinkStack(lstack, &t2);
	//打印链栈数据
	while (!IsEmptyLinkStack(lstack)){
		Teacher* teacher = (Teacher*)TopLinkStack(lstack);
		printf("Name:%s Age:%d\n",teacher->name,teacher->age);
		PopLinkStack(lstack);
	}	
	//销毁链表
	DestroyLinkStack(lstack);
}

int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}
未经允许不得转载:一亩三分地 » 栈(Stack)