天天看点

栈ADT链式实现及数组实现

栈ADT  栈的名词就不解释了

先是链式实现:

三个代码  测试 头文件 及函数实现源码

stack.h:

/*  栈类型的头文件  */    
  
  
#ifndef STACK_H_  
#define STACK_H_   
  
  
struct Node;                                    //先声明,就可以在下面使用,而不必因定义在后面而产生冲突  
  
   
/*  一般类型定义  */    
typedef int ElementType;                        //抽象数据类型    
typedef struct Node * PtrToNode;  
typedef PtrToNode Stack;  

  
  
/*  特定于程序的声明  */     
struct Node {  
    ElementType element;    
    PtrToNode	next;  
};  
  
  
/*  函数原型  */    
void MakeEmpty ( Stack s );  
int IsEmpty ( Stack s );
void Push ( ElementType x, Stack s );  
void Pop ( Stack s );  
Stack CreateStack ( void );
void DisposeStack ( Stack s );
ElementType Top ( Stack s );
  
 
#endif  
           

stack.c:

/*  list.c  -- 支持栈操作的函数  */    
  
  
#include <stdio.h>    
#include <stdlib.h>  
#include "stack.h"    
  
  
/*  接口函数  */    
  
  
/*  把栈初始化为空栈  */  
void MakeEmpty ( Stack s )
{  
	if ( NULL == s )
	{
		printf ( "必须首先创建一个栈!\n" );
	}
	else
	{
		while ( !IsEmpty ( s ) )
		{
			Pop ( s );
		}
	}
}  
  
/*  检查栈是否为空  */    
int IsEmpty ( Stack s )    
{    
    return ( NULL == s -> next );  
}    
   
/*  创建一个栈  */
Stack CreateStack ( void )
{
	Stack s;

	s = ( Stack )malloc ( sizeof ( struct Node ) );

	if ( NULL == s )
	{
		printf ( "创建失败!\n" );

		return NULL;
	}
	else
	{
		s -> next = NULL;

		MakeEmpty ( s );

		return s;
	}
}

/*  栈顶插入元素x  */
void Push ( ElementType x, Stack s )
{
	PtrToNode tmp;								//此处为了清楚起见,别用 Stack.

	tmp = ( Stack )malloc ( sizeof ( struct Node ) );

	if ( NULL == tmp )
	{
		printf ( "插入失败!\n" );
	}
	else
	{
		tmp -> element = x;						//别忘了赋值这一步.
		tmp -> next = s -> next;
		s -> next = tmp;
	}
}
		
/*  栈顶弹出元素  */
void Pop ( Stack s )
{
	if ( IsEmpty ( s ) )
	{
		;
	}
	else
	{
		PtrToNode tmp;

		tmp = s -> next;
		s -> next = s -> next -> next;

		free ( tmp );
	}
}

/*  返回栈顶元素  */
ElementType Top ( Stack s )
{
	if ( IsEmpty ( s ) )
	{
		return 0;								//栈为空,返回0,代表错误!
	}
	else
	{
		return ( s -> next -> element );
	}
}

/*  销毁栈  */
void DisposeStack ( Stack s )
{
	PtrToNode tmp;
	PtrToNode p;

	p = s -> next;

	free ( s );
	s = NULL;									//想想实参形参,外面s的值不会因为这里而改变.
	
	//while ( NULL != p -> next )
	//{
	//	tmp = p -> next;
	//	free ( p );
	//	p = tmp;
	//}

	//free ( p );

	while ( NULL != p )
	{
		tmp = p -> next;
		free ( p );
		p = tmp;
	}
}
           

test.c:

#include "stack.h"
#include <windows.h>
#include <stdio.h>

int main ( void )
{

	Stack s = CreateStack ( );					//测试CreateStack ( )函数

	printf ( "%d\n", ( IsEmpty ( s ) ) );		//测试IsEmpty ( s )函数
	
	Push ( 1, s );
	Push ( 2, s );

	printf ( "%d\n", ( Top ( s ) ) );

	Pop ( s );

	printf ( "%d\n", ( Top ( s ) ) );

	printf ( "%d\n", ( IsEmpty ( s ) ) );

	MakeEmpty ( s );

	printf ( "%d\n", ( IsEmpty ( s ) ) );

	DisposeStack ( s );

	system ( "pause" );

	return 0;

}
           

继续阅读