数据结构:链栈小练习(c语言)

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");
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值