1. 程式人生 > >【資料結構】鏈式棧的實現(C語言)

【資料結構】鏈式棧的實現(C語言)

棧的鏈式儲存稱為鏈式棧,鏈式棧是一種特殊的單鏈表,它的插入和刪除規定在單鏈表的同一端進行。鏈式棧的棧頂指標一般用top表示。(個人理解:相當於只對單鏈表的第一個結點進行操作

鏈式棧要掌握以下基本操作:

1、建立一個空鏈式棧

2、判斷鏈式棧是否為空

3、讀鏈式棧的棧頂節點值

4、輸出鏈式棧中個結點的值

5、向鏈式棧中插入一個值為x的結點(進棧)

6、刪除鏈式棧的棧頂結點(出棧)

執行環境:Dev-C++5.11

以下是標頭檔案:

#ifndef LNKSTACK_H_INCLUDED
#define LNKSTACK_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
typedef struct link_node
{
	int info;
	struct link_node *next;
}N;

/*建立一個空的鏈式棧*/
N *init()
{
	return NULL;
}

/*對鏈式棧進行初始化*/
N *creat(N *top)
{
	int x;
	N *p;
	printf("以輸入-1為結束\n");
	scanf("%d",&x);
	while(x!=-1)
	{
		p=(N*)malloc(sizeof(N));
		p->info=x;
		p->next=top;
		top=p;
		scanf("%d",&x);
	}
	return top;
}

/*判斷鏈式棧是否為空*/
int isempty(N *top)
{
	return (top?0:1);/*返回1這說明是空*/
} 

/*取得鏈式棧的棧頂結點值*/
int read(N *top)
{
	if(!top)
	{
		printf("\n該鏈式棧是空的\n");exit(1);
	}
	return top->info;
} 

/*輸出鏈式棧中各結點的值*/
void display(N *top)
{
	N *p=top;
	if(!top)
	{
		printf("該鏈式棧是空的\n");
	}
	else
	{
		while(p)
		{
			printf("%d  ",p->info);
			p=p->next;
		}
	}
}

/*鏈式棧的插入操作*/
N *insert(N *top,int x)
{
	N *q=top,*p;
	p=(N*)malloc(sizeof(N));
	p->info=x;
	p->next=top;
	top=p;
	return top;
}

/*鏈式棧的刪除操作*/
N *dele(N *top)
{
	N *p=top;
	if(!top)
	{
		printf("\n該鏈式棧是空的,無法進行刪除\n");return NULL; 
	}
	top=top->next;
	free(p);
	return top; 
} 
#endif // LNKSTACK_H_INCLUDED

以下是主程式:

#include "stdio.h"
#include "lnkstack.h"
int main ()
{
	int x; 
	N *p,*q,*top;
	while(1)
	{
		top=init();
		top=creat(top);
		display(top);
		printf("\n插入的數為:");
		scanf("%d",&x);
		top=insert(top,x);
		display(top);
		printf("\n刪除操作:");
		top=dele(top);
		display(top);
		printf("\n判斷鏈式棧是否為空:");
		if(isempty(top))
		{
			printf("是\n");
		} 
		else
		{
			printf("否\n");
		}
		printf("獲取鏈式棧的棧頂結點值:%d\n\n",read(top));		
	}
	return 0;
}

執行結果: