做了些无用功,写了栈的遍历和查找,这个应该是多此一举了……主函数写了简单的程序测试,测试没问题
#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");
}