数据结构学习之路3 堆栈的基本操作

本文介绍了一个简单的栈数据结构实现,包括创建、压栈、弹栈等基本操作,并通过示例程序验证了栈的功能。此外,还实现了元素查找及位置返回功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做了些无用功,写了栈的遍历和查找,这个应该是多此一举了……主函数写了简单的程序测试,测试没问题
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
struct Stack{
	int data[MAXSIZE];
	int top;
};
typedef Stack *stack;
stack creat(){
	stack p;
	p = (stack)malloc(sizeof(Stack));
	p ->top = -1;
	return p;
}
void push(int x, stack p){
	if(p ->top + 1 == MAXSIZE){
		cout << "栈已满";
		return;
	}
	else{
		p ->data[++ (p ->top)] = x;
		return;
	}
}
int pop(stack p){
	if(p ->top == -1){
		cout << "栈已空";
		return -1;
	}
	else
	return p ->data[(p ->top) --];
}
int findKth(int x, stack p){
	Stack s = *p;
	while(p ->data[p ->top] != NULL){
		if(p ->data[p ->top] == x){
			int a = p ->top + 1;
			*p = s;
			return a;
		}
		else p ->top --;
	}
	*p = s;
	return -1;
}
int find(int i, stack p){
	if(i > p ->top + 1 || i < 1){
		cout << "超出查找范围";
		return NULL;
	}
	else
		return p ->data[i - 1];
}
void display(stack p){
	for(int i = p ->top; i >= 0; i --){
		cout << p ->data[i] << endl;
	}
}
void main(){
	stack p = creat();
	push(1, p);
	push(5, p);
	push(2, p);
	push(7, p);
	display(p);
	int a = findKth(2, p);
	cout << a << endl;
	int b = find(3, p);
	cout << b << endl;
	display(p);
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值