《数据结构与算法分析——C语言描述》第三章 链栈实现(C语言)

链栈:采用链式存储的栈。
特点是入栈出栈操作均在链表表头进行。
优点是不存在栈满上溢的情况,便于多个栈共享存储空间和提高其效率。(后半句没怎么理解)
实现如下(带头结点):

//栈的链式存储——链栈 
#include 
#include 

#define ElementType int
#define N 10
typedef struct Z{
	ElementType data;
	struct Z *next;
}Stack;

typedef Stack* S;

S make_empty( S ptrs );                 //初始化栈 
int IsEmpty( S ptrs );                 //判断栈是否为空,若为空,返回1,否则返回0 
void push( ElementType x, S ptrs );    //入栈
ElementType pop( S ptrs );             //出栈并返回栈顶元素
ElementType GetTop( S ptrs );          //读取栈顶元素 
int length( S ptrs );                  //求栈长 
int main ( void )
{
	S ptrs;
	
	ptrs = make_empty( ptrs );
	
	int i = 0;
	for( i = 0; i < N; i++ )
		push( i, ptrs );
	
	int len = length( ptrs );
	 
	if( IsEmpty( ptrs ) )
		printf( "栈空\n" );
	else
		printf( "栈不空,有元素%d个\n", len );
	
	S p = ptrs;
	while( p -> next != NULL ){
		printf( "%d ", p -> next -> data );
		p = p -> next;
	}
	printf( "\n" );
	
	ElementType x = pop( ptrs );
	printf( "%d\n", x );
	
	x = GetTop( ptrs );
	printf( "%d", x );
	
	return 0;
} 

S make_empty( S ptrs )
{
	ptrs = ( S )malloc( sizeof( Stack ) );
	if( ptrs == NULL ){
		printf( "请求空间错误\n" );
		exit(0);
	} 
	ptrs -> next = NULL;
}

int IsEmpty( S ptrs )
{
	return ptrs -> next == NULL;
}

void push( ElementType x, S ptrs )
{
	S p;
	p = ( S )malloc( sizeof( Stack )  );
	if( ptrs == NULL ){
		printf( "请求空间错误\n" );
		exit(0);
	}
	p -> data = x;
	p -> next = ptrs -> next;
	ptrs -> next = p;
}

ElementType pop( S ptrs )
{
	if( IsEmpty( ptrs ) ){
		printf( "栈空\n" );
		exit(0);
	}
	ElementType temp = ptrs -> next -> data;
	S p = ptrs -> next;
	ptrs -> next = ptrs -> next -> next;
	free( p );
	return temp;
} 

ElementType GetTop( S ptrs )
{
	if( IsEmpty( ptrs ) ){
		printf( "栈空\n" );
		exit(0);
	}
	return ptrs -> next -> data;
}

int length( S ptrs )
{
	int len = 0;
	while( ptrs -> next != NULL ){
		len++;
		ptrs = ptrs -> next;
	}
	return len;
}

你可能感兴趣的:(数据结构与算法分析)