1. 程式人生 > >C語言實現鏈棧的初始化&進棧&出棧&讀取棧頂元素

C語言實現鏈棧的初始化&進棧&出棧&讀取棧頂元素

/*連結串列實現棧的一系列操作*/
 
#include<stdio.h>
#include<stdlib.h> 

#define OK 1
#define ERROR 0

typedef struct node
{
	int data;
	struct node *next;
}LinkStackNode,*LinkStack;

/**********************各個子函式的定義*********************/
void initStack(LinkStack *top);       //初始化鏈棧 
int push(LinkStack top,int n);        //鏈棧進棧操作 
void pop(LinkStack top);              //鏈棧出棧操作 
int getTop(LinkStack top,int *s);     //讀取鏈棧棧頂元素 

int main()
{
	LinkStack top;
	int choice;
	while(true)
	{
        printf("*****************Please enter your choice*****************\n\n");
        printf("                choice 1:Stack initialization\n");
        printf("                choice 2:Into the stack\n");
        printf("                choice 3:Out of the stack\n");
        printf("                choice 4:Read the stack elements\n");
        printf("                choice 0:exit\n\n");
	 	scanf("%d",&choice);
		switch(choice)
		{
			case 1:
				initStack(&top);
				break;
			case 2:
				int n;
				printf("Please enter the number into the stack elements:");
				scanf("%d",&n);
				(push(top,n)==1)?printf("%d個元素依次進棧成功\n",n):printf("%d個元素依次進棧失敗\n",n);	
				break;
			case 3:
				pop(top);
				break;
			case 4:
				int* s;
				(getTop(top,s)==1)? printf("棧頂元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目運算子
				break;		
			case 0:
				exit(0);
				break;
			default:
				printf("ERROR!!\n");
				exit(0);
				break;
		}
	}
	return 0;
}

/**********************各個子函式功能的實現*********************/
void initStack(LinkStack *top)
{   //初始化 
	*top=(LinkStack)malloc(sizeof(LinkStackNode));  //帶頭結點的單鏈表 
	(*top)->next=NULL; 
} 
 
int push(LinkStack top,int n)	//進棧 ,將元素壓入棧中 
{		
	LinkStackNode *temp;
	int n1,n2;
	printf("Please enter into the stack elements in turn:\n");  
	for(n1=0;n1<n;n1++)
	{
		scanf("%d",&n2);
		temp=(LinkStackNode *)malloc(sizeof(LinkStackNode));  //結點申請空間 
		if(temp==NULL) return ERROR;  //申請空間失敗
		temp->data=n2;
		temp->next=top->next;          //採用頭插法儲存元素 
		top->next=temp; 
	}
	return OK;
}

void pop(LinkStack top)          //棧頂元素出棧 
{           
	int a;
	LinkStackNode *temp;
	if(top->next==NULL)
	{               //棧為空,出棧失敗 
		printf("An empty stack error!!!!\n");
	}
	else
	{
		temp=top->next;
		a=temp->data;
		top->next=temp->next;
		free(temp);
		printf("棧頂元素%d出棧成功.\n",a);  
	}  
}

int getTop(LinkStack top,int *s)        //獲讀取棧頂元素 
{    
	if(top->next==NULL)              //棧為空,讀取棧頂元素失敗 
	{ 
		return ERROR;
	}
	else
	{
		*s=(top->next)->data;           //讀取棧頂元素,不出棧 
		return OK;
	}
}