栈有两种实现方式:单链表、数组
本文是单链表实现方式的基本操作。
数据结构:
struct Node { ElementType Element; PtrToNode Next; };
数据类型:
typedef int ElementType; typedef struct Node *PtrToNode; typedef PtrToNode Stack;
基本操作:
/* Return 1 if stack is NULL */ int IsEmpty( Stack S ) { return S->Next == NULL; }
NOTICE THIS FUNCTION
/* Create a void stack */ Stack CreateStack( void ) { Stack S;/* S point to heap */ S = malloc( sizeof( struct Node ) ); if( S == NULL ) FatalError( "Out of space!!!" ); S->Next = NULL; MakeEmpty( S ); return S; }
/* Make a stack empty */ void MakeEmpty( Stack S ) { /*if( S == NULL ) Error( "Must use CreateStack first" ); else while( !IsEmpty( S ) ) Pop( S );*/ if( S != NULL ) while( !IsEmpty( S ) ) Pop( S ); else/* S == NULL */ Error( "Must use CreateStack first" ); }
/* Push X into stack 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; } }
/* Abtain the top element of stack S */ ElementType Top( Stack S ) { if( !IsEmpty( S ) ) return S->Next->Element; Error( "Empty stack" ); return 0;/* Return value used to avoid warning */ }
/* Pop the top element of stack S */ void Pop( Stack S ) { PtrToNode FirstCell; if( IsEmpty( S ) ) Error( "Empty stack" ); else { FirstCell = S->Next; S->Next = S->Next->Next; free( FirstCell ); } }
/* Dispose stack */ void DisposeStack( Stack S ) { MakeEmpty( S ); free( S ); }
/* Print all the elements of stack */ void PrintStack( Stack S ) { Stack sTmp; sTmp = S; while( sTmp->Next != NULL ) { printf( "%d ",sTmp->Next->Element ); sTmp = sTmp->Next; } }
NOTICE THIS FUNCTION
/* Main function */ int main() { int iReturn; Stack Sa = CreateStack( ); Push( 1, Sa ); Push( 2, Sa ); Push( 3, Sa ); Push( 4, Sa ); Push( 5, Sa ); Pop( Sa ); Pop( Sa ); PrintStack( Sa ); return 0; }
细心的读者不难注意到(这句话),两个函数前面标明了NOTICE THIS FUNCTION,在第一个函数中:
/* Create a void stack */ Stack CreateStack( void ) { Stack S;/* S point to heap */ S = malloc( sizeof( struct Node ) ); if( S == NULL ) FatalError( "Out of space!!!" ); S->Next = NULL; MakeEmpty( S ); return S; }
Stack S;/* S point to heap */
再看第二个函数也就是main函数:
/* Main function */ int main() { int iReturn; Stack Sa = CreateStack( ); Push( 1, Sa ); Push( 2, Sa ); Push( 3, Sa ); Push( 4, Sa ); Push( 5, Sa ); Pop( Sa ); Pop( Sa ); PrintStack( Sa ); return 0; }
Stack Sa = CreateStack( );
在这里调用了CreateStack(),这个函数是带有返回值的,并且返回的是一个指针,注意:函数不能返回指向栈内存的指针!
但是这里的指针是指向堆内存的?所以可以返回?以上测试时可以正常进行的!
时间: 2024-10-13 21:42:03