1. 程式人生 > >資料結構示例之用連結串列實現棧

資料結構示例之用連結串列實現棧

以下是“使用連結串列實現棧”的簡單示例:

1. 用c語言實現的版本

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

struct s_node
{
	int data;
	struct s_node *next;
};

typedef struct s_node* pNode;
pNode stack = NULL;
int pCount = 0;

/* 列印棧的內容 */
void print_stack()
{
	pNode temp = NULL;
	temp = stack;
	if (temp == NULL)
	{
		printf("The stack is empty!\n");
	}
	else
	{
		while (temp != NULL)
		{
			printf("[%d]", temp->data);
			temp = temp->next;
		}
		printf("\n");
	}
}

/* 入棧,從頭部插入 */
void push(int value)
{
	if (stack)
	{
		pNode newnode;
		newnode = (pNode)malloc(sizeof(s_node)); 
		if (!newnode)
		{
			printf("malloc fail, please check!");
			return;
		}
		newnode->data = value;
		newnode->next = stack;
		stack = newnode;
		++pCount;
	}
	else
	{
		stack = (pNode)malloc(sizeof(s_node));
		if (!stack)
		{
			printf("malloc fail, please check!");
			return;
		}
		stack->data = value;
		stack->next = NULL;
		++pCount;
	}
}

/* 出棧,從頭部刪除 */
void pop(int *value)
{
	pNode top;

	if (stack != NULL)
	{
		top = stack;
		stack = stack->next;
		*value = top->data;
		free(top);
		--pCount;
	}
	else
	{
		pCount = 0;
	}
}

void main()
{
	pNode point;
	int select;
	int value;

	printf("(1)Input a stack data.\n");
	printf("(2)Output a stack data.\n");
	printf("(3)Exit\n");
	printf("Please select your choice: ");
	scanf("%d", &select);
	do
	{
		switch (select)
		{
		case 1:
			printf("Before push, the stack content (top->bottom) is: \n");
			print_stack(); /* 列印棧的內容 */
			printf("Please input the digit: ");
			scanf("%d", &value);
			push(value);
			printf("After push, the stack content (top->bottom) is: \n");
			print_stack();
			break;
		case 2:
			printf("Before pop, the stack content (top->bottom) is: \n");
			print_stack(); /* 列印棧的內容 */
			if (pCount) {
				pop(&value);
				printf("The output value is: [%d].\n", value);
				printf("After pop, the stack content (top->bottom) is: \n");
				print_stack();
			}
			else
			{
				printf("The stack is empty, it can not be poped!");
			}
			break;
		default:
			printf("Please input the right choice!");
			break;
		}

		printf("\n(1)Input a stack data.");
		printf("\n(2)Output a stack data.");
		printf("\n(3)Exit.");
		printf("\nPlease select your choice: ");
		scanf("%d", &select);
	} while (select != 3);
}

執行結果如下所示: