一、顺序栈
#include <stdio.h>
#define maxSize 100
typedef struct{
int data[maxSize];
int top;
}SqStack;
//&是运用了C++的引用参数
//初始化栈,将栈顶指针置为-1
void initStack(SqStack &st){
st.top=-1;
}
//栈为空时返回1,否则返回0
int isEmpty(SqStack st){
if (st.top==-1)
return 1;
else
return 0;
}
//进栈,入栈成功返回1,否则返回0
int push(SqStack &st, int x){
if (st.top==maxSize-1)
return 0;
++(st.top);
st.data[st.top]=x;
return 1;
}
//出栈,出栈成功返回1,否则返回0
int pop(SqStack &st, int &x){
if (st.top==-1)
return 0;
x=st.data[st.top];
--(st.top);
return 1;
}
//打印当前栈中元素
void printStack(SqStack st){
for (int i=0; i<=st.top; i++){
printf ("%d ", st.data[i]);
}
}
int main(){
SqStack s;
initStack(s);
push(s, 5);
push(s, 3);
push(s, 20);
int x;
pop(s, x);
printf("x=%d\n", x);
printStack(s);
return 0;
}
二、链栈
#include <stdio.h>
#include <stdlib.h>
typedef struct lineStack{
int data;
struct lineStack *next;
}lineStack;
//链栈初始化,使用引用型参数
void initStack(lineStack *&lst){
lst=(lineStack*)malloc(sizeof(lineStack));
lst->next=NULL;
}
//栈为空返回1,否则返回0
int isEmpty(lineStack *lst){
if (lst->next==NULL)
return 1;
else
return 0;
}
//入栈
void push(lineStack *lst, int x){
lineStack *temp;
temp=(lineStack*)malloc(sizeof(lineStack));
temp->next=NULL;
temp->data=x;
temp->next=lst->next;
lst->next=temp;
}
//出栈,返回1出栈成功,否则失败
int pop(lineStack *lst, int &x){
lineStack *temp;
if (lst->next==NULL)
return 0;
temp=lst->next;
x=temp->data;
lst->next=temp->next;
free(temp);
return 1;
}
//打印链栈
void printLineStack(lineStack *lst){
lineStack *p=lst->next;
while (p!=NULL){
printf("%d ", p->data);
p=p->next;
}
}
int main(){
lineStack *ls;
initStack(ls);
push(ls, 5);
push(ls, 232);
push(ls, 24);
int x;
pop(ls, x);
printf("x=%d\n", x);
printLineStack(ls);
return 0;
}