数据结构:栈(Stack )

(Stack):是只允许在一端进行插入删除线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。

栈顶(Top):线性表允许进行插入删除的那一端。
栈底(Bottom):固定的,不允许进行插入和删除的另一端。
空栈:不含任何元素的空表。

栈又称为后进先出(Last In First Out)的线性表,简称LIFO结构

栈的常见基本操作
InitStack(&S):初始化一个空栈S。
StackEmpty(&S):判断一个栈是否为空,若栈为空则返回true,否则返回false。
Push(&S, x):进栈(栈的插入操作),若栈S未满,则将x加入使之成为新栈顶。
Pop(&S):出栈(栈的删除操作),若栈S非空,则弹出栈顶元素,并用x返回。
GetTop(S, &x):读栈顶元素,若栈S非空,则用x返回栈顶元素。
DestroyStack(&S):栈销毁,并释放S占用的存储空间(“&”表示引用调用)。

栈源码

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

typedef struct Node {
	int data;
	struct Node* next;
}Node;

Node* initStack() {
	Node* L = (Node *)malloc(sizeof(Node));
	if (!L) return NULL;
	L->data = 0;
	L->next = NULL;
	return L;
}

void push(Node *L,int data) {
	Node* last = L;
	Node* new_node = initStack();
	new_node->data = data;

	while (last->next != NULL) {
		last = last->next;
	}
	last->next = new_node;
}

int isEmpty(Node* L) {
	if (L->data == 0 && L->next == NULL) {
		return 1;
	}
	else {
		return 0;
	}
}

void pop(Node *L) {
	if (isEmpty(L)) {
		return;
	} else {
		Node* last = L;
		Node* pre = L;
		while (last->next != NULL) {
			pre = last;
			last = last->next;
		}
		free(last->next);
		pre->next = NULL;
	}
}

void printStack(Node *L) {
	if (isEmpty(L)) {
		return;
	} else {
		Node* last = L->next;
		while (last) {
			printf("last->data = %d \r\n",last->data);
			last = last->next;
		}
	}
}

int main() {
	Node* node = initStack();
	push(node, 1);
	push(node, 2);
	push(node, 3);
	pop(node);
	pop(node);
	printStack(node);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

7yewh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值