数据结构中的栈是一种受限制的线性表!他只能在一段进行操作!他的特性是后进先出。
可以用两种方式来实现栈的存储!
1:栈的链式存储
#include "stdio.h"
#define TYPE struct student
#define LEN sizeof(TYPE)
#define NULL 0
struct student{
int no[10];
int top;
};
TYPE *init(){
TYPE *stack=(TYPE *)malloc(LEN);
stack->top=-1;
return stack;
}
TYPE *push(TYPE *stack){
int no;
printf("please input the no:");
scanf("%d",&no);
stack->top++;
stack->no[stack->top]=no;
return stack;
}
TYPE *pull(TYPE *stack){
printf("%d",stack->no[stack->top]);
stack->no[stack->top]=NULL;
stack->top--;
return stack;
}
void clearStack(TYPE *stack){
free(stack);
}
main(){
int i;
TYPE *stack;
stack=init();
for(i=0;i<10;i++){
stack=push(stack);
}
pull(pull(stack));
getch();
}
2:栈的顺序存储
#include "stdio.h"
#define TYPE struct student
#define NULL 0
#define LEN sizeof(TYPE)
struct student{
int no;
TYPE *next;
};
TYPE *push(int n){
int i;
TYPE *header,*pf,*ps;
for(i=1;i<=n;i++){
ps=(TYPE *)malloc(LEN);
printf("please input the no:");
scanf("%d",&ps->no);
if(i==1) {
pf=ps;
ps->next=NULL;
}
else{
ps->next=pf;
pf=ps;
}
}
return ps;
}
int getLength(TYPE *stack){
int i=0;
while(stack!=NULL){
i++;
stack=stack->next;
}
return i;
}
TYPE *pull(TYPE *stack){
TYPE *header;
int i,length;
printf("%d/n",stack->no);
return stack->next;
}
main(){
TYPE *stack;
stack=push(4);
pull(pull(pull(pull(stack))));
getch();
}
可以用两种方式来实现栈的存储!
1:栈的链式存储
#include "stdio.h"
#define TYPE struct student
#define LEN sizeof(TYPE)
#define NULL 0
struct student{
int no[10];
int top;
};
TYPE *init(){
TYPE *stack=(TYPE *)malloc(LEN);
stack->top=-1;
return stack;
}
TYPE *push(TYPE *stack){
int no;
printf("please input the no:");
scanf("%d",&no);
stack->top++;
stack->no[stack->top]=no;
return stack;
}
TYPE *pull(TYPE *stack){
printf("%d",stack->no[stack->top]);
stack->no[stack->top]=NULL;
stack->top--;
return stack;
}
void clearStack(TYPE *stack){
free(stack);
}
main(){
int i;
TYPE *stack;
stack=init();
for(i=0;i<10;i++){
stack=push(stack);
}
pull(pull(stack));
getch();
}
2:栈的顺序存储
#include "stdio.h"
#define TYPE struct student
#define NULL 0
#define LEN sizeof(TYPE)
struct student{
int no;
TYPE *next;
};
TYPE *push(int n){
int i;
TYPE *header,*pf,*ps;
for(i=1;i<=n;i++){
ps=(TYPE *)malloc(LEN);
printf("please input the no:");
scanf("%d",&ps->no);
if(i==1) {
pf=ps;
ps->next=NULL;
}
else{
ps->next=pf;
pf=ps;
}
}
return ps;
}
int getLength(TYPE *stack){
int i=0;
while(stack!=NULL){
i++;
stack=stack->next;
}
return i;
}
TYPE *pull(TYPE *stack){
TYPE *header;
int i,length;
printf("%d/n",stack->no);
return stack->next;
}
main(){
TYPE *stack;
stack=push(4);
pull(pull(pull(pull(stack))));
getch();
}