數據結構:鏈棧的實現

棧的原理不再細說(可以參考嚴蔚敏版 或 王道考研版的數據結構),只貼代碼。

主要應用到的是單鏈表的頭插法

頭插法,顧名思義,每次插入新的結點都在頭部插入,新插入的結點成爲首元結點。

對於單鏈表定義規則:插入結點的時候只能從頭部插入,刪除結點的時候只能從頭部刪除,這樣的單鏈表其實就是一個棧。正是基於這樣的準則實現的鏈棧。

這裏給的是不帶頭結點實現鏈棧,但是學習過程中帶頭結點和不帶頭結點的鏈棧都應該會實現

/* 採用不帶頭結點的單鏈表實現棧 */ 

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

#define ElemType int

typedef struct LinkNode{
	ElemType data;
	struct LinkNode *next;
} LinkNode, *LinkStack; 

// 初始化棧爲空 
void InitStack(LinkStack &s)
{
	s = NULL; 
}
// 入棧操作 
bool StackPush(LinkStack &s, ElemType e)
{
	LinkNode* node = (LinkNode *)malloc(sizeof(LinkNode));
	if(node == NULL){ // 申請內存空間失敗 
		return false;
	}
	node->data = e;
	node->next = s; 
	s = node; 
	return true;
}
// 出棧操作
bool StackPop(LinkStack &s) 
{
	if(s == NULL){	// 如果棧爲空 
		return false;
	}
	LinkNode *tmp = s;
	s = s->next;
	free(tmp); // 刪除此棧頂結點 
	return true;
}
ElemType GetTop(LinkStack s)
{
	if(s == NULL){ // 棧爲空 
		exit(1);
	}
	return s->data;	
}

// 判斷棧是否爲空 
bool StackIsEmpty(LinkStack &s)
{
	return (s == NULL) ? true : false; 
}

int main()
{
	LinkStack s;
	InitStack(s);
	for(int i = 0; i < 10; i++){
		StackPush(s, i+1);
	}
	
	for(int i = 0; i < 10; i++){
		printf("%d\n", GetTop(s));
		StackPop(s);
	}
	printf("\n%d\n", StackIsEmpty(s));
	return 0;
}

 

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