栈的链式存储和操作实现

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef int ElemType;
typedef struct SingleNode
{
	ElemType data;
	struct SingleNode* next;
}Stack;
#endif
 
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
/*************************************/
//初始化链栈
/*************************************/
void initStack(Stack* S,int ms)
{
	S->next=NULL;
 } 
/*************************************/
//向链栈中插入如一个元素
/*************************************/
void push(Stack* S,ElemType item)
{
	Stack* p=malloc(sizeof(Stack));
	p->data=item;
	p->next=S->next;
	S->next=p;
 }
/**************************************/
//从栈链中删除一个元素并返回
/**************************************/
ElemType pop(Stack* S)
{
	if(S->next==NULL)
	{
	  printf("Linked stack is empty! exit");
	  exit(1);	
	}
	Stack* p=S->next;
	ElemType x=p->data;
	S->next=p->next;
	free(p);
	return x;
 }
/****************************************/
//读取栈顶元素
/****************************************/
ElemType peek(Stack* S)
{
	if(S->next==NULL)
	{
		printf("Linked stack is empty! exit");
		exit(1);
	}
	return S->next->data;
 } 
/****************************************/
//检查栈链是否为空
/****************************************/
int emptyStack(Stack* S)
{
	return S->next==NULL;
 }
/****************************************/
//清除栈链为空
/****************************************/
void clearStack(Stack* S)
{
	Stack* p=S->next;
	while(p!=NULL)
	{
		Stack* q=p->next;
		free(p);
		p=q;
	}
	S->next=NULL;
 } 
/******************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
#include "栈在链接存储下运算的算法.c"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) 
{
    int i,x,y,z;
	int a[8]={3,8,5,17,9,30,15,22};
	Stack r,*S=&r;
	
	initStack(S,1);
	
	for(i=0;i<8;i++)
	{
		push(S,a[i]);
	
	}
	x=pop(S);
	y=pop(S);
	z=pop(S);
	printf("%d %d %d\n",x,y,z);
	push(S,68);
	x=peek(S);
	y=pop(S);
	z=peek(S);
	printf("%d %d %d\n",x,y,z);
	
	push(S,60);
	
	while(!emptyStack(S))
	{
		printf("%d",pop(S));
		printf("\n");
	}
	clearStack(S);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值