链栈的一些操作

     利用链表实现栈的一些操作,主要是为了练习链表的使用。

     程序主要包括:

                                      1.进栈

                                      2.出栈

                                      3打印栈表

                                      4.销毁栈表


//Filename:StackLink.cpp
//Writed by CaoLichen
//本程序利用链表实现栈的各种操作

#include<stdio.h>
#include<stdlib.h>

//定义结点类型
typedef struct Node
{
	int data;
	struct Node *next;
}SLink;


//进栈
void Push(SLink *top, int data)
{
	SLink *tmp;
	tmp = (SLink *)malloc(sizeof(SLink));
	tmp->data = data;

	tmp->next = top->next;						//进栈
	top->next = tmp;

	printf("进栈成功!\n");
}

//出栈
void Pop(SLink *top)
{
	if(top->next == NULL){
		printf("出栈失败!\n");
		return ;
	}

	SLink *tmp;
	tmp = top->next;
	top->next = tmp->next;						//重建连接
	free(tmp);									//释放空间
	printf("出栈成功!\n");
}

//打印栈表
void PrintStack(SLink *top)
{
	printf("栈内情况为:\n");
	
	if(top->next == NULL){
		printf("空栈!\n");
		return;
	}

	top = top->next;
	while(top != NULL){
		printf("%d ",top->data);
		top = top->next;
	}

	printf("\n");
}

//销毁栈
void ClearStack(SLink *top)
{
	SLink *tmp;		
	while(top != NULL){
		tmp = top;
		top = top->next;
		free(tmp);
	}
}

int main()
{
	SLink *top;									//定义栈顶指针
	top = (SLink *)malloc(sizeof(SLink));		//申请空间
	top->next = NULL;							//初始化

	int i;
	for(i = 0; i < 19; i ++){
		Push(top,i);							//进栈
		PrintStack(top);						
	}

	for(i = 0; i < 19; i ++){
		Pop(top);								//出栈
		PrintStack(top);
	}

	ClearStack(top);							//销毁栈
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值