一.数据类型声明

#include<stdio.h>
struct LQNode { //结点结构体
	int data; //数据域
	Node next; //指针域
};
typedef LQNode * Node; //结点结构体指针变量
typedef Node List; //结点结构体头指针变量

二.带有头结点的链栈基本操作

/*带头结点的链栈*/

//1.初始化
void initStack(List list) {
	list = new LQNode; //把结点结构体的内存首地址赋值给头指针变量
	list->next = NULL;
}
//2.判栈空
int isEmpty(List list) {
	if (list->next == NULL) {
		return 1;
	}
	else
		return;
}
//3.进栈(注:链栈基本上不会出现栈满的情况)
void push(List list,int x) {
	Node s;
	s = new LQNode;
	s->data = x;

	//插入操作(因为栈FIFL的特性,故使用头插法)
	s->next = list->next;
	list->next = s;
}
//4.出栈
int pop(List list,int &x) {
	Node s;
	if (list->next==NULL) //栈空不能出栈,返回0
		return 0;
	
	//删除操作
	s = list->next;
	x = s->data;
	list->next = list->next->next;
	delete(s);

	return 1;
}

三.不带头结点的链栈基本操作

/*不带头结点的链栈*/

//1.初始化
void initStack1(List list) {
	list = NULL;
}

//2.判栈空
int isEmpty1(List list) {
	if (list == NULL)
		return 1;
	else
		return 0;
}
//3.进栈
void push1(List list,int x) {
	Node s = new LQNode;
	s->data = x;

	//插入操作
	s->next = list;
	list = s;
}
//4.出栈
int pop1(List list,int &x) {
	Node s;
	if (list == NULL) //栈空不能出栈,返回0
		return 0;

	//删除操作
	s = list;
	x = s->data;
	list = list->next;
	delete(s);

	return 1;
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐