stack c 实现

头文件

#ifndef _Stack_H
#define _Stack_H

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef PtrToNode Position;
typedef int Item;

int isEmpty(Stack stack);
Stack createStack(void);
void push(Item item,Stack stack);
Item top(Stack stack);
void pop(Stack stack);
void makeEmpty(Stack stack);
void printStack(Stack stack);

#endif

struct Node{
	Item item;
	struct Node* next;
};

源文件

#include"stack.h"

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

int isEmpty(Stack stack){
	
	return stack->next==NULL;
}

Stack createStack(void){
	
	Stack S;
	S=malloc(sizeof(struct Node));
	if(S==NULL){
		puts("stack arrange fail");
		exit(1);
	}
	S->next=NULL;
	return S;
}

void push(Item item,Stack stack){
	
	Position tmp;
	tmp=malloc(sizeof(struct Node));
	if(tmp==NULL){
		puts("stack arrange fail");
		exit(1);
	}
	
	tmp->item=item;
	tmp->next=stack->next;
	stack->next=tmp;
}

Item top(Stack stack){
	
	if(isEmpty(stack))
	{puts("stack null");
	 exit(1);
	}
	return stack->next->item;
}
void pop(Stack stack){
	
	if(isEmpty(stack))
	{puts("stack null");
	 exit(1);
	}
	Stack p=stack->next;
	stack->next=p->next;
	free(p);
}
void makeEmpty(Stack stack){
	
	while(!isEmpty(stack)){
		pop(stack);
	}
}

void printStack(Stack stack){
	
	if(isEmpty(stack))
	{puts("stack null");
	 exit(1);
	}
	Position p=stack->next;
	while(p){
		printf("%d\t",p->item);
		p=p->next;
	}
}
测试

#include"stack.h"

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

int main(){
	
	Stack s=createStack();
	if(isEmpty(s))
	  printf("stack is null\n");
	
	push(2,s);
	push(22,s);
	push(25,s);
	push(12,s);
	push(4,s);
	
	if(isEmpty(s))
	  printf("stack is null\n");
	  
	printStack(s);
/*	
	int i;
	while(!isEmpty(s)){
	  i=top(s);
	  printf("%d\n",i)	;
	  pop(s);
	}
*/
    makeEmpty(s);
    if(isEmpty(s))
      printf("s is null\n");
	push(12,s);
	printStack(s);	
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值