mooc2.2堆栈数组实现

本文介绍了一个简单的栈实现方法,使用数组作为数据结构的基础,详细讲解了入栈和出栈的操作流程,包括检查栈满和栈空的状态,以及如何进行元素的添加和删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的入栈出栈操作,数组实现

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define max 10000
typedef struct snode* stack;
struct snode
{
  int data[max];
  int top;	
 }; 
 
 
 void push(stack head,int x)//入栈操作 
 {  if(head->top==max-1)
    {
	  printf("堆栈满了!\n");//入栈要看栈满了没 
	  return; 
	}	
	else
	{
		head->data[++(head->top)]=x;//x放在top上面一个位置 即top+1 
		return;
	}
 
 }
 
 
 int pop(stack head)//出栈操作,return删除的值,并在栈中删除该值 
 {  if(head->top==-1)//出栈要看栈空不空,top为-1时,栈则为空 
   {
 	printf("栈空!!\n"); 
	 return 0; 
   }
  else
   return (head->data[(head->top)--]);
  } 
  
  void print(stack head)
  {  int i;
  	if(head->top==-1)
  	{printf("栈空!!\n");
	  return;
	  }
	else
	{
		for(i=0;i<=head->top;i++)
		printf("%d ",head->data[i]);
		return ;
	}
	   
  	
  	
  }
  
  int main()
  { int i=-1,x;
  	struct snode A;
  	stack head=A.data ;
  	do
  	{printf("输入!");	
	   i++;
	  scanf("%d",&head->data[i]);
     
	  }while(head->data[i]);
	  head->top=i-1;
	printf("入栈操作,请输入加入的元素x\n");
	scanf("%d",&x);
	 push(head,x);
	printf("操作后:\n");
	 print(head);
	 printf("\n出栈操作\n");
	 printf("删除的元素为%d\n",pop(head));
	 printf("操作后:");
	 print(head); 
  	return 0;
  	
   } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值