0.栈的建立及头文件声明
#include<stdio.h>
#include<stdlib.h>
struct Stack
{
int data;
struct Stack* next;
};
struct Stack* init_Stack(struct Stack*);
struct Stack* push_Stack(struct Stack*, int);
int pop_Stack(struct Stack*, int *);
int stack_Top(struct Stack*, int *);
int count_stack(struct Stack *);
void disp_stack(struct Stack*);
void destroy_stack(struct Stack *head);
1.初始化栈
//init_Stack
struct Stack* init_Stack(struct Stack*head)
{
struct Stack*p = (struct Stack*)malloc(sizeof(struct Stack));
p->data = -1;
p->next = NULL;
printf("\n初始化成功\n");
return p;
}
2.入栈
//push_Stack
struct Stack* push_Stack(struct Stack*head, int x)
{
struct Stack*p = (struct Stack*)malloc(sizeof(struct Stack));
p->data = x;
p->next=head->next;
head->next = p;
return head;
}
3.出栈
//pop_Stack
int pop_Stack(struct Stack*head, int *d)
{
struct Stack*p = head->next;//退栈
if (p == NULL)
{
printf("该栈已空\n");
return 0;
}
head->next = p->next;
*d = p->data;
free(p);
printf("退栈的数为%5d\n", *d);
}
4.取栈顶元素
int stack_Top(struct Stack*head, int *num)
{
struct Stack*p = head->next;
if (p == NULL)
{
return 0;
}
*num = p->data;
printf("栈顶元素为%5d\n", *num);
return 1;
}
5.计算栈的元素个数
int count_stack(struct Stack *head)
{
struct Stack *p;
int k = 0;
p = head;
while (p != NULL)
{
k++;
p = p->next;
}
return k;
}
6.显示栈
void disp_stack(struct Stack*head)
{
struct Stack*p;
printf("链栈\n");
if (head == NULL)
{
printf("链栈已空\n");
}
else
{
p = head;
while (p != NULL)//loop
{
printf("%4d\n", p->data);
p = p->next;
}
}
printf("\n");
}
7.销毁栈
void destroy_stack(struct Stack *head)
{
struct Stack *p, *q;
p = head;
while (p != NULL)
{
q = p;
p = p->next;
free(q);
}
printf("删除成功");
}
8.测试程序(main)
//text
void main()
{
struct Stack *head;
int n, top, num, length, i;
head = NULL;
head = init_Stack(head);//初始化
/*入栈*/
head = push_Stack(head, 35);
head = push_Stack(head, 45);
head = push_Stack(head, 55);
head = push_Stack(head, 65);
head = push_Stack(head, 75);
head = push_Stack(head, 85);
disp_stack(head);
stack_Top(head, &n);
length = count_stack(head);
for (i = 0; i < length; i++)
{
pop_Stack(head, &num);
}
destroy_stack(head);
system("pause");
}