您的位置:首页 > 理论基础 > 数据结构算法

用链表实现堆栈数据结构

2011-05-14 16:55 302 查看
包含主要的功能,压栈、出栈、读数据~~~~~~~~~~~~~

/************************************************************************/
/* author : thomas
E-mail: chenhua308@gmail.com                                         */
/************************************************************************/


头文件 stack.h

#include <stdio.h>
#include <malloc.h>
/*
**interface of stack data-structure module
*/
typedef int T;  //you can change int into whatever data type you want
typedef struct tag
{
T element;
struct tag *link;
} node;
typedef node *STACK;
/*
** push
** push a new value into the stack, the parameter is the value needed to push
*/
void push( STACK *top, T num );
/*
** pop
** just delete the top node
*/
void pop( STACK *top );
/*
** access
** return the top node's value
*/
T access( STACK top );
/*
** is_empty
** judge the state of stack ---empty? full? or ……
*/
int is_empty( STACK top );
/*
** destroy
** destroy the stack
*/
void destroy( STACK *top );
/*
** creat
** create stack
*/
STACK creat( T num );
/*
** print
** print the value of stack
*/
void print( STACK top );


源文件 stack.c

#include "stack.h"
/*****************************************************************************/
STACK creat( T num )
{
node *p;
p = ( node * )malloc( sizeof( node ) );
p -> element = num;
p -> link = NULL;
return p;
}

void push( STACK *top, T num )
{
node *p;
p = ( node * )malloc( sizeof( node ) );
p -> element = num;

if ( *top == NULL )
{
*top = p;
p -> link = NULL;
}
else
{
p -> link = *top;
*top = p;
}
}
T access( STACK top )
{
return top -> element;
}
int is_empty( STACK top )
{
return top == NULL;
}
void pop( STACK *top )
{
node *p;
p = *top;
*top = (*top) -> link;
free(p);
}
void destroy( STACK *top )
{
node *temp;
while ( *top != NULL )
{
temp = *top;
*top = (*top) -> link;
free(temp);
}
//	return top;
}
void print( STACK top )
{
int i = 0;
printf("****************************************************************/n");
if ( top == NULL )
{
printf("the stack is empty! /n");
}
else
{
while ( top != NULL )
{
i++;
printf("the %d number is: %d /n", i, top -> element);
top = top -> link;
}
}
};
//test the functions
void main(int argc, char *argv[])
{
STACK stack1 = NULL;
print(stack1);
stack1 = creat( 4 );
print(stack1);
push( &stack1, 6 );
print(stack1);
push( &stack1, 2 );
push( &stack1, 8 );
print(stack1);
push( &stack1, 1 );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: