1. 程式人生 > >資料結構中棧的鏈式結構—鏈棧的基本操作

資料結構中棧的鏈式結構—鏈棧的基本操作

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

typedef int Elemtype;
typedef struct StackNode{
	Elemtype data;
	struct StackNode *next;
}StackNode,*LinkStackPtr;

typedef struct LinkStack{
	LinkStackPtr top;
	int size;
}LinkStack;

//初始化 
void init_Stack(LinkStack *S)//沒有頭結點,初始化不需要為top申請空間 
{
		S->top=NULL;
		S->size=0;
		printf("OK\n");
}
//進棧 
void push_Stack(LinkStack *S,Elemtype e)
{
	LinkStackPtr p=(LinkStackPtr)malloc(sizeof(StackNode));
	if(p!=NULL)
	{
		p->data=e;
		p->next=S->top;
		S->top=p;
		S->size++;
		printf("OK\n");
	}
}
//出棧 
void pop_Stack(LinkStack *S,Elemtype *e)
{
	if(S->size!=NULL)
	{
		LinkStackPtr p=S->top;
		*e=S->top->data;
		S->top=S->top->next;
		free(p);
		p=NULL;
		S->size--;
		printf("OK\n");
	}
}
//清空鏈棧 
void clear_Stack(LinkStack *S)
{
	LinkStackPtr p,q;
	p=S->top;
	while(p!=NULL)
	{
		q=p->next;
		free(p);
		p=q;
	}
	S->top=NULL;
	S->size=NULL; 
}
//列印 
void print_Stack(LinkStack *S)
{
	LinkStackPtr p=S->top;
	if(!p)
	{
		printf("NULL\n");
		return;
	}
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n"); 
}

int main()
{
	LinkStack S;
	Elemtype e;int i;
	while((i=getchar())!='#')
	{
		switch(i)
		{
			case '0':init_Stack(&S);break;
			case '1':scanf("%d",&e);push_Stack(&S,e);break;
			case '2':pop_Stack(&S,&e);break;
			case '3':print_Stack(&S);break;
			case '4':clear_Stack(&S);break;
			case '5':printf("棧的當前長度為%d\n",S.size);break;
		}
	
 	} 
	return 0;
}