文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>栈-链表实现(C)

栈-链表实现(C)

时间:2010-03-15  来源:xiantaozhaowei

/* 异常处理头文件 */
/* fatal.h */
#include <stdio.h>
#include <stdlib.h>

#define Error( Str ) FatalError( Str )
#define FatalError( Str ) fprintf( stderr, "%s\n", Str ), exit( 1 )


/* Header file for stack: list version */
/* stackli.h */
typedef int ElementType;
#ifndef _Stack_h
#define _Stack_h

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty( Stack S);
Stack CreateStack( void );
void DisposeStack( Stack S );
void MakeEmpty( Stack S );
void Push( ElementType X, Stack S );
ElementType Top( Stack S );
void Pop( Stack S );

#endif


/* stackli.c */
#include "stackli.h"
#include "fatal.h"
#include <stdlib.h>

struct Node
{
  ElementType Element;
  PtrToNode Next;
};

int
IsEmpty( Stack S )
{
  return S->Next == NULL;
}

Stack
CreateStack( void )
{
  Stack S;
  S = malloc( sizeof( struct Node ) );
  S->Next = NULL;
  MakeEmpty( S );
  return S;
}

void
MakeEmpty( Stack S )
{
  if( S == NULL )
    Error( "Must use CreateStack first" );
  else
    while( !IsEmpty( S ) )
      Pop( S );
}
    
void
DisposeStack( Stack S )
{
  MakeEmpty( S );
  free( S );
}

void
Push( ElementType X, Stack S )
{
  PtrToNode TmpCell;

  TmpCell = malloc( sizeof( struct Node ) );
  if( TmpCell == NULL )
    FatalError( "Out of space!!!" );
  else
    {
      TmpCell->Element = X;
      TmpCell->Next = S->Next;
      S->Next = TmpCell;
    }
}

ElementType
Top( Stack S )
{
  if( !IsEmpty( S ) )
    return S->Next->Element;
  Error( "Empty stack" );
  return 0;
}
    
void
Pop( Stack S )
{
  PtrToNode FirstCell;

  if( IsEmpty( S ) )
    Error( "Empty stack" );
  else
    {
      FirstCell = S->Next;
      S->Next = S->Next->Next;
      free( FirstCell );
    }
}


#include <stdio.h>
#include "stackli.h"

int
main()
{
  Stack S;
  int i;

  S = CreateStack();
  for( i = 0; i < 10; i++ )
    Push( i, S );

  while( !IsEmpty( S ) )
    {
      printf( "%d\n", Top( S ) );
      Pop( S );
    }

  DisposeStack( S );
  return 0;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载