4.18作业

本文详细介绍了使用C语言实现的两种栈数据结构:顺序栈(seq_stack)和链式栈(link_stack),包括栈的创建、空栈检查、元素入栈、出栈以及内存管理函数。
摘要由CSDN通过智能技术生成
#ifndef __SEQ_STACK_H__
#define __SEQ_STACK_H__
#define MAX 8
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct seq_stack
{
	int   data[MAX];
	int   top;
}seq_stack,*seq_p;

seq_p create_stack();                //创建一个顺序栈                      
int empty_stack(seq_p S);
int fell_stack(seq_p S);
void push_stack(seq_p S,int data);


void show_stack(seq_p S);
void pop_stack(seq_p S);
void free_stack(seq_p *S);


#endif
#include "seq_stack.h"
seq_p create_stack()
{
	seq_p S=(seq_p)malloc(sizeof(seq_stack));
	if(S==NULL)
	{
		printf("内存申请失败\n");
		return NULL;
	}
	S->top=-1;
	return S;
}
int empty_stack(seq_p S)
{
	if(S==NULL)
	{
		printf("参数为空\n");
		return -1;
	}
	return S->top==-1?1:0;

}
int fell_stack(seq_p S)
{
	if(S==NULL)
	{
		printf("入参为空\n");
		return -1;
	}
	return S->top==MAX-1?1:0;
}
void push_stack(seq_p S,int data)
{
	if(S==NULL)
	{
		printf("入参为空\n");
		return;
	}
	if(fell_stack(S))
	{
		printf("栈已满,无法输入\n");
			return;
	}
	S->top++;
	S->data[S->top]=data;
}
void show_stack(seq_p S)
{
	if(S==NULL)
	{
		printf("入参为空\n");
		return;
	}
	if(empty_stack(S))
	{
		printf("栈为空,无需输出\n");
		return;
	}
/*	for(;S->top>-1;S->top--)
	{
		printf("%d\n",S->data[S->top]);

	}*/
	for(int i=S->top;i>-1;i--)
	{
		printf("%-4d",S->data[i]);
	}
	putchar(10);
}
void pop_stack(seq_p S)
{
	if(S==NULL)
	{
		printf("入参为空\n");
		return;
	}
	if(empty_stack(S))
	{
		printf("栈为空,无法出栈\n");
		return;
	}
	printf("出栈元素为%d\n",S->data[S->top]);

	S->top--;

}
void free_stack(seq_p *S)
{
	if(S==NULL||*S==NULL)
	{
		printf("入参为空\n");
		return;
	}
//	(*S)->top=-1;
	free(*S);
    *S=NULL;

}
#ifndef __LINK_STACK_H__
#define __LINK_STACK_H__

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
	int data;
	struct node *next;
}node,*node_p;

node_p create_stack(int data);
void push_stack(node_p *T,int data);
int empty_stack(node_p T);
void show_stack(node_p T);
void pop_stack(node_p *T);






#endif
#include "linK_stack.h"
node_p create_stack(int data)
{
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("内存申请失败\n");
		return NULL;
	}
	new->next=NULL;
	new->data=data;
	return new;
}
void push_stack(node_p *T,int data)
{
	node_p new = create_stack(data);
	new->next=*T;
	*T=new;
}
int empty_stack(node_p T)
{
	return T==NULL?1:0;
}
void show_stack(node_p T)
{
	if(empty_stack(T))
	{
		printf("栈为空,无需输出\n");
		return;
	}
	node_p p=T;
	while(p!=NULL)
	{
		printf("%d->",p->data);
        p=p->next;
	}
	printf("NULL\n");

}
void pop_stack(node_p *T)
{
	node_p del=*T;
	*T=(*T)->next;
	free(del);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值