王道數據結構:棧順序存儲和鏈式存儲以及基本操作的實現(C語言版)

只允許在一端進行插入或刪除操作的線性表。

對於n個不同元素進棧,出棧序列的個數爲(卡特蘭數)

順序棧基本操作的實現代碼如下:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#define MaxSize 10
//棧的順序存儲 
typedef struct {
	int data[MaxSize];
	int top;	
}SqStack;
//初始化棧 
void InitStack(SqStack &s){
	s.top=-1;
	for(int i=0;i<10;i++){
		s.data[i]=0;
	}
	printf("初始化完畢\n");
}
//判空 
void StackEmpty(SqStack s){
	if(s.top==-1){
		printf("棧爲空\n");
	}else{
		printf("棧不爲空\n");
	}
}
//入棧 
bool Push(SqStack &s,int e){
	if(s.top==MaxSize-1){
		printf("棧已滿\n"); 
		return false;
	}
	s.data[++s.top]=e;
	return true;
}
//出棧 
bool Pop(SqStack &s,int &e){
	if(s.top==-1){
		printf("棧已空\n");
		return false;
	}
	e=s.data[s.top--];
	printf("出棧棧頂元素,值爲%d\n",e);
	return true;
}
//獲取棧頂元素 
bool GetTop(SqStack &s,int &x){
	if(s.top==-1){
		printf("棧爲空\n");
		return false;
	}
	x=s.data[s.top];
	printf("棧頂元素爲:%d\n",x);
	return true;
}
//打印棧 
void PrintStack(SqStack s){
	if(s.top==-1){
		for(int i=0;i<10;i++){
			//printf("|       |\n");
			printf("|_ _ _ _|\n");
		}
	}
	if(s.top!=-1){
		for(int i=0;i<MaxSize-s.top;i++){
			printf("|_ _ _ _|\n");
		}
		while(s.top!=-1){
			printf("|___%d___|\n",s.data[s.top]);
			s.top--;
		}
	}
}
int main(){
	SqStack s;
	InitStack(s);
	StackEmpty(s);
	Push(s,1);
	Push(s,2);
	Push(s,3);
	Push(s,4);
	StackEmpty(s);
	PrintStack(s);
	int e,x;
	Pop(s,e);
	PrintStack(s);
	GetTop(s,x);
}

代碼運行截圖如下:

鏈式棧基本操作的實現代碼如下:

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

//棧的鏈式存儲
typedef struct Linknode{
	int data;
	struct Linknode *next;
}Linknode,*LiStack; 

//初始化棧 
void InitStack(LiStack &L){
	L =(Linknode*)malloc(sizeof(Linknode));//創建頭節點 
	L->next=NULL;//初始化爲空	
}

//棧判空 
bool StackEmpty(LiStack L){
	if(L->next==NULL){
		printf("棧爲空\n");
		return false;
	}
	else{
		printf("棧不爲空\n");
		return true;
	}
}

//入棧 
bool Push(LiStack &L,int e){
 Linknode *s=(Linknode *)malloc(sizeof(Linknode));
 s->data=e;
 s->next=L->next;
 L->next=s; 
 return true;

}

//出棧 
bool Pop(LiStack &L,int &e){
	if(L->next==NULL){
		printf("棧已空\n");
		return false;
	}
	Linknode *p=L->next;
	e=p->data;
	L->next=p->next;//成鏈 
	printf("出棧元素值爲%d\n",e);
	free(p);
	return true;
} 
bool GetTop(LiStack L,int x){
		if(L->next==NULL){
		printf("棧已空\n");
		return false;
	}
	Linknode *p=L->next;
	x=p->data;
	printf("棧頂元素值爲%d\n",x);
	return true;
}
void PrintStack(LiStack L){
	Linknode *n=L->next;
	while(n!=NULL){
		printf("|___%d___|\n",n->data);
		n=n->next;
	}
}
int main(){
	LiStack s;
	InitStack(s);
	StackEmpty(s);
	Push(s,1);
	Push(s,2);
	Push(s,3);
	Push(s,4);
	StackEmpty(s);
	PrintStack(s);
	int e,x;
	Pop(s,e);
	PrintStack(s);
	GetTop(s,x);
} 

代碼運行截圖如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章