现在的位置: 首页 > 综合 > 正文

数据结构C语言实现系列——链式堆栈

2014年06月05日 ⁄ 综合 ⁄ 共 1284字 ⁄ 字号 评论关闭
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

#define STACK_MAX 100

typedef int elemType ;


/************************************************************************/
/*             以下是关于链式堆栈操作的6种算法        */
/************************************************************************/

typedef struct
{
	elemType* base;
	elemType* top;
	int size;
}Stack;

/* 1.初始化栈s为空 */
void initStack(Stack* s)
{
	elemType *head;
	head=(elemType *)malloc(STACK_MAX*sizeof(elemType));
	if(head==NULL)
	{
		printf("Error----> Mallco Fail!\n");
		return;
	}
	s->base=s->top=head;
	s->size=STACK_MAX;
}

/* 2.获取栈顶元素 */
elemType getTop(Stack *s)
{
	if(s->top==s->base)
	{
		printf("Error----> Empty Stack!\n");
		return -1;
	}
	return *(s->top-1);
}

/* 3.入栈 */
void Push(Stack *s,elemType e)
{
	if(s->top==NULL)
	{
		printf("Error----> Empty Stack!\n");
		return;
	}
	*(s->top)=e;
	s->top++;
}
/* 4.出栈 */
elemType Pop(Stack *s)
{
	if(s->top==s->base)
	{
		printf("Error----> Empty Stack!\n");
		return -1;
	}
	s->top--;
	return *s->top;
}

/* 5.打印栈 */
void StackTrave(Stack *s)
{
	elemType *i;
	int len=0;
	if(s->top==s->base)
	{
		printf("Error----> Empty Stack!\n");
		return;
	}
	for(i=s->base;i<s->top;i++)
	{
		printf("%d  ",*i);
		len++;
	}
	printf("\nlen=%d\n",len);
}


int main(int argc, char* argv[])
{
	Stack myStack;
	int i;
	int a[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; 
	initStack(&myStack);
	for(i=0;i<10;i++)
	{
		Push(&myStack,a[i]);
	}
	StackTrave(&myStack);
	printf("出栈=%d\n",Pop(&myStack));
	StackTrave(&myStack);
	while(1);
}

抱歉!评论已关闭.