课堂内容
顺序栈
#include "stack.h"
int main(int argc, const char *argv[])
{
seq_p S=create_stack();
push_stack(S,11);
push_stack(S,22);
push_stack(S,33);
push_stack(S,44);
push_stack(S,55);
show_stack(S);
free_stack(&S);
return 0;
}
#ifndef __STACK_H__
#define __STACK_H__
#include <stdio.h>
#include <stdlib.h>
#define MAX 8
typedef int datatype;
typedef struct
{
datatype data[MAX];
int top;
}seq_stack,*seq_p;
//堆区申请顺序栈的空间
seq_p create_stack();
//入栈\压栈
void push_stack(seq_p S,datatype);
//判空
int empty_stack(seq_p S);
//判满
int full_stack(seq_p S);
//输出栈
void show_stack(seq_p S);
//出栈\弹栈
void pop_stack(seq_p S);
//释放顺序栈
void free_stack();
#endif
#include "stack.h"
//堆区申请顺序栈的空间
seq_p create_stack()
{
//堆区申请空间
seq_p S=(seq_p)malloc(sizeof(seq_stack));
//判断空间是否申请成功
if(S==NULL)
{
printf("空间申请失败\n");
return NULL;
}
//申请成功后,给data和top初始化
S->top=-1; //栈中没有元素时,让top指向-1
return S;
}
//入栈\压栈
void push_stack(seq_p S,datatype data)
{
//入参为空的判断
if(S==NULL)
{
printf("空间申请失败\n");
return;
}
//判满
if(full_stack(S))
{
printf("栈已满\n");
return;
}
//入栈
//先加再压,先自增top指针,再将数据压入栈
S->top++;
S->data[S->top]=data;
}
//判空
int empty_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return -1;
}
return S->top==-1?1:0;
}
//判满
int full_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return -1;
}
return S->top==MAX-1?1:0;
}
//输出栈
void show_stack(seq_p S)
{
if(S==NULL)
{
printf("空间申请失败\n");
return;
}
if(empty_stack(S))
{
printf("栈为空\n");
return;
}
//要求输出顺序和栈操作的顺序一致
for(int i=S->top;i>=0;i--)
{
printf("%-4d",S->data[i]);
}
putchar(10);
}
//出栈\弹栈
void pop_stack(seq_p S)
{
if(S==NULL)
{
printf("空间申请失败\n");
return;
}
if(empty_stack(S))
{
printf("栈为空\n");
return;
}
printf("出栈元素为%d\n",S->data[S->top]);
}
//释放顺序栈
void free_stack(seq_p *S)
{
if(S==NULL || *S==NULL)
{
printf("入参为空\n");
return;
}
free(*S);
*S=NULL;
}
链表栈
#include "stack.h"
int main()
{
//申请栈顶指针
node_p T=NULL; //此时栈中没有元素
push_stack(&T,23);
pop_stack(&T);
push_stack(&T,69);
push_stack(&T,77);
pop_stack(&T);
return 0;
}
#ifndef __STACK_H__
#define __STACK_H__
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*node_p;
//申请结点
node_p create_node(int data);
//入栈
void push_stack(node_p *T,int data);
//判空
int empty_stack(node_p T);
//出栈
void pop_stack(node_p *T);
//输出栈
void show_stack(node_p T);
#endif
#include "stack.h"
//申请结点
node_p create_node(int data)
{
node_p new=(node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data=data;
return new;
}
//入栈
void push_stack(node_p *T,int data)
{
//不再需要入参为空的判断,因为T就在栈区
node_p new=create_node(data);
new->next=*T; //让新结点指向原来的栈顶元素
*T=new; //让栈顶指针指向新结点
}
//判空
int empty_stack(node_p T)
{
return T==NULL?1:0;
}
//出栈
void pop_stack(node_p *T)
{
node_p del=*T;
*T=(*T)->next;
printf("要出栈的元素为%d\n",del->data);
free(del);
}
//输出栈
void show_stack(node_p T)
{
if(empty_stack(T))
{
printf("栈为空,无需输出\n");
return;
}
node_p p=T;
while(p!=NULL)
{
printf("%d->\n",p->data);
return;
}
}