【数据结构/Data Structure】栈/Stack(一):一些基本概念

一、栈 ADT

        栈,作为一种抽象的数据类型(Abstract Data Type,ADT),具有先进后出、后进先出的特性(Last in First out,LIFO)。我们可以将栈想象成一个硬币存钱筒,一枚枚硬币就相当于一个个数据。栈就是这样一种单向出口的数据容器,存入栈中的数据会在栈顶,依次向下,取出栈中的数据也只能取出栈顶的数据。

        类比存钱筒的操作存钱、取钱的操作,我们可以很自然的想到,栈的一些操作。

        (1)Push() ,将某个数据压入栈中的操作称作 Push 。

        (2)Pop() ,将栈中的数据,也就是栈顶的数据弹出的操作称为 Pop 。

        (3)Top() ,用于查看当前栈顶数据而不进行弹出的操作。

        (4)IsEmpty() ,用于检查栈是否为空的操作。

        上面说的栈是一种抽象的数据结构,在不同的情况下会有不同的实现方式,要注意区分。

二、使用不同方式实现一个栈

        1、使用数组实现

        定义一个数组,同时定义一个表示栈顶位置的变量 top,当 top 为 -1 时,代表此时栈内没有元素。在这里都使用全局变量,方便进行代码编写。数组为固定大小,也可以使用动态数组,此处为了方便不再进行赘述。

        栈的四种操作都通过 top 变量的进行。

#include <stdio.h>  
#include <stdbool.h>  

#define MAX_SIZE 101

int Stack[MAX_SIZE];
int top = -1;

void Push(int x) {
	if (top == MAX_SIZE - 1) {
		printf("ERROR: stack overflow\n");
		return;
	}
	Stack[++top] = x;
}

void Pop() {
	if (top == -1) {
		printf("ERROR: no element to pop\n");
		return;
	}
	top--;
}

int Top() {
	return Stack[top];
}

bool IsEmpty() {
	if (top == -1) return true;
	return false;
}

void Print() {
	int i;
	for (i = 0; i <= top; i++) 
		printf("%d ", Stack[i]);
	printf("\n");
}

int main() {
	Push(3); Print();
	Push(5); Print();
	Push(11); Print();
	Push(8); Print();
	Push(34); Print();
}

         测试代码运行的结果:

         2、使用链表实现

        对于单向链表来说,不论是将数据从头节点插入,变为新的头节点,还是将数据从头节点取出,并将头节点删除,都是很容易实现的操作。而这正好也实现了我们希望的栈的 Push() 和 Pop() 操作。同样 IsEmpty() 只需要检查头节点是否为空即可,Top() 只需要查看头节点里的数据即可。

        下面的代码利用C中的链表实现了储存整型的Stack,节点是存储在堆上的,暂时不考虑栈溢出的情况。

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

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

struct Node* Push(struct Node* s, int x) {
	struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
	temp->data = x;
	temp->next = s;
	return temp;
}

struct Node* Pop(struct Node* s) {
	if (s == NULL) return s;
	struct Node* temp = s->next;
	free(s);
	return temp;	
}

int Top(struct Node* s) {
	if (s != NULL) return s->data;
	printf("ERROR nothing on top\n");
	return NULL;
}

bool IsEmpty(struct Node* s) {
	if (s != NULL) return true;
	return false;
}

void Print(struct Node* s) {
	printf("\n");
	while (s != NULL) {
		printf("%d  ", s->data);
		s = s->next;
	}
}

int main() {
	struct Node* top = NULL;	//创建了一个空的栈
	top = Push(top, 5);
	top = Push(top, 3);
	top = Push(top, 8);
	top = Push(top, 13);
	Print(top);
	top = Pop(top);
	top = Pop(top);
	Print(top);
	return 0;
}

        测试代码运行的结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值