链式栈基本操作的实现

在单链表的基础上来实现链式栈就比较容易了

首先,定义连个结构体,一个是结点的结构体,还有一个是链式栈的结构体,链式栈的结构体中有一个指针指向栈顶。

依次实现下面的操作:

1.初始化:初始化只需要将栈顶指针置为空即可;在这需要注意要先申请一个栈,才能进行初始化。

2.销毁栈:如果栈不为空,则先将没一个元素进行出栈操作,最后释放栈空间;

3.入栈:首先创建一个结点,再将这个结点入栈,最后修改栈顶指针;

4.出栈:先移动栈顶指针到栈顶的next,在销毁原来的栈顶结点;

5.取栈顶元素:直接将栈顶元素赋给形参;

代码如下:

linkstack.h

#pragma once

typedef char LinkStackNodeType;


typedef struct LinkStackNode {
	LinkStackNodeType data;
	struct LinkStackNode* next;
	
}LinkStackNode;
 
typedef struct LinkStack{
	LinkStackNode* top;
}LinkStack;
//初始化
void LinkStackInit();
//销毁
void LinkStackDestroy(LinkStack* stack);
//入栈
void LinkStackPush(LinkStack* stack,LinkStackNodeType value);
//出栈
void LinkStackPop(LinkStack* stack);
//取栈顶元素
int LinkStackTop(LinkStack* stack,LinkStackNodeType* top);


linkstack.c

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


void LinkStackInit(){
	LinkStack* stack = (LinkStack*)malloc(sizeof(LinkStack));
	if(stack == NULL){
		//申请内存失败
		return;
	}
	stack->top = NULL;
	return;
}

void LinkStackDestroy(LinkStack* stack){
	if(stack == NULL){
		return;
	}
	if(stack->top != NULL){
		LinkStackPop(stack);
	}
	free(stack);
	return;
}


void LinkStackPush(LinkStack* stack,LinkStackNodeType value){
	if(stack == NULL){
		//非法输入
		return;
	}
	LinkStackNode* new_node = (LinkStackNode*)malloc(sizeof(LinkStackNode));
	if(new_node == NULL){
		//申请失败
		return;
	}
	new_node->data = value;
	new_node->next = stack->top;
	stack->top = new_node;
	return;
}

void LinkStackPop(LinkStack* stack){
	if(stack == NULL){
		return;
	}
	if(stack->top == NULL){
		//空栈
		return;
	}
	LinkStackNode* to_delete = stack->top;
	stack->top = to_delete->next;
	free(to_delete);
	return;
}

int LinkStackTop(LinkStack* stack, LinkStackNodeType* value){
	if(stack == NULL || value == NULL){
		return 0;
	}
	if(stack->top == NULL){
		//空栈
		return 0;
	}
	*value = stack->top->data;
	return 1;
}

test.c

#include <stdio.h>
#define TEST_HEADER printf("\n============================%s=============================\n",__FUNCTION__)

void LinkStackPrintChar(LinkStack* stack,const char* msg){
	printf("[%s]\n",msg);
	LinkStackNode* cur = stack->top;
	for(;cur!=NULL;cur=cur->next){
		printf("[%c] ",cur->data);
	}
	printf("\n");
}

void TestLinkStack(){
	TEST_HEADER;
	LinkStack stack;
	LinkStackInit(&stack);
	LinkStackPush(&stack,'a');
	LinkStackPush(&stack,'b');
	LinkStackPush(&stack,'c');
	LinkStackPush(&stack,'d');

	LinkStackPrintChar(&stack,"入栈四个元素");
	LinkStackPop(&stack);
	LinkStackPrintChar(&stack,"出栈一个元素");

	LinkStackNodeType value;
	int ret = LinkStackTop(&stack,&value);
	printf("ret expected 1,actual %d\n",ret);
	printf("value expeted c , actual %c\n",value);

}

int main(){
	TestLinkStack();
	return 0;
}





阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页