下面是C语言实现栈的基本操作,代码比较简单。

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

#define INIT_STACK_SIZE 100
#define ADD_STACK_SIZE 100

typedef int ElemType;
typedef struct Stack
{
	ElemType *base;
	ElemType *top;
	int Stack_Size;
}Stack,*pStack;

void prinf();
bool init_stack(pStack S);
bool push(pStack S,ElemType data);
bool pop(pStack S,ElemType *data);
void DestoryStack(pStack S);
void DisplayStack(pStack S);

int main()
{
	int iChoice,i,data;
	Stack stack ;
	if(!init_stack(&stack))	//initial stack
		return 0;
	for(i = 1; i < 100;++i)//for debug,push from 1 to 100;
		push(&stack,i);
	DisplayStack(&stack);	//print stack
	prinf();		
	while(1)
	{
		prinf();
		scanf("%d",&iChoice);
		switch(iChoice)
		{
		case 1:
			{
				printf("Iuput data:\n");
				scanf("%d",&data);
				push(&stack,data);
				DisplayStack(&stack);
				break;
			}
		case 2:
			{
				ElemType e;
				pop(&stack,&e);
				DisplayStack(&stack);
				break;
			}
		case 3:
			printf( "Node of The Stack is %d\n" , stack.top - stack.base);
			break;
		default :
			break;
		}
	}
	return 0;
}

bool init_stack(pStack S)
{

	S->base = (ElemType *)calloc(INIT_STACK_SIZE,sizeof(ElemType));
	if(!S->base)
	{
		printf("Allocate Memory Error\n");
		return 0;
	}
	S->top = S->base;
	S->Stack_Size = INIT_STACK_SIZE;//initial size 100
	return 1;
}

bool push(pStack S,ElemType data)
{
	if((S->top - S->base) >= S->Stack_Size) //Stack is full
	{
		S->base = (ElemType *)realloc(S->base , ( S->Stack_Size + ADD_STACK_SIZE) * sizeof(ElemType));
		S->top = S->base + S->Stack_Size;
		S->Stack_Size += ADD_STACK_SIZE;//New Size
	}
	*S->top = data;//push data
	S->top++;
	return 1;
}

bool pop(pStack S,ElemType *data)
{
	if(S->top == S->base) //Stack is empty
	{
		printf("Empty\n");
		return 0;
	}
	*data = *(--S->top);
	return 1;
}

void DisplayStack(pStack S)
{
	ElemType *p = S->base;
	int i = 0;
	while(p != S->top)
	{
		printf("Stack No,%d : %d \n",1 + i,*p);
		p++;
		i++;
	}
}


void prinf()
{
	printf ("1:Insert Node\n");
	printf ("2:delete Node\n");
	printf ("3:Length of stack\n");
}

标签:DataStructure