stack c 实现

公冶泰
2023-12-01

头文件

#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);	
}



 类似资料: