head.h
#ifndef __EE_H__
#define __EE_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datadef;
#define MAX 10
typedef struct
{
datadef data[MAX]; // 数据域
int top; // 指针域
} *stack, Stack;
stack creat(); // 创建新栈
int push(stack S, datadef s); // 压栈
int pop(stack S); // 出栈
int output(stack S); // 正向遍历
int T_output(stack S); // 反向遍历
void S_free(stack L); // 释放 //链表释放
#eneif
fun.c
#include "head.h"
stack creat() // 创建新栈
{
stack S = (stack)malloc(sizeof(Stack));
if (S == NULL)
{
return NULL;
}
S->top = -1;
return S;
}
/*
int insert(linklist L,linklist p,datedef e) //p后插入 (中插)
{
linklist s=creat(0);
s->date=e;
s->next=p->next;
p->next=s;
L->len++;
return 0;
}
int indel(linklist L,linklist p) //p后删除 (中删)
{
linklist q=p->next;
p->next=q->next;
L->len--;
free(q);
q=NULL;
return 0;
}
*/
int push(stack S, datadef s) // 压栈
{
if (S == NULL || S->top == MAX)
{
printf("入栈失败\n");
return -1;
}
S->top++;
S->data[S->top] = s;
return 0;
}
int pop(stack S) // 出栈
{
if (S->top == -1 || S == NULL)
{
printf("出栈失败\n");
}
printf("出栈的元素是: %d\n", S->data[S->top]);
S->top--;
}
int output(stack S) // 正向遍历
{
if (S->top == -1 || S == NULL)
{
printf("遍历失败\n");
return -1;
}
printf("正向遍历:");
for (int i = 0; i <= S->top; i++)
{
printf("%d\t", S->data[i]);
}
puts("");
return 0;
}
int T_output(stack S) // 反向遍历
{
if (S->top == -1 || S == NULL)
{
printf("遍历失败\n");
return -1;
}
printf("反向遍历:");
for (int i = S->top; i >= 0; i--)
{
printf("%d\t", S->data[i]);
}
puts("");
return 0;
}
void S_free(stack L) // 释放
{
if (L == NULL)
{
return;
}
int n = L->top;
for (int i = 0; i < n; i++)
{
pop(L);
}
free(L);
L = NULL;
}
main.c
#include "head.h"
int main(int argc, const char *argv)
{
stack S = creat();
int n;
datadef s, e;
while (1)
{
printf("你要入栈的元素:");
scanf("%d", &s);
push(S, s);
printf("你要继续入栈吗?N/n\n");
char c;
scanf(" %c", &c);
if (c == 'n' || c == 'N')
{
break;
}
}
output(S);
T_output(S);
pop(S);
output(S);
T_output(S);
S_free(S);
#if 0
printf("你要尾插的元素个数:");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
printf("你要尾插的元素是:");
scanf("%d",&s);
r_insert(L,s); //尾插
}
output(L);
bubble(L); //排序
output(L);
L_free(L); //链表释放
#endif
}