栈有别于队列,属于先进后出,比较简单,直接看源代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM 10 typedef struct _StackNode { int data; struct _StackNode *next; }StackNode; typedef struct _StackList { StackNode *top; //栈顶指针,标记栈当前位置,动态地随push和pop函数调用变化而变化 }StackList; /** * 栈置空 * */ void InitStack( StackList *s ) { s->top = NULL; } /** * 判断栈是否为空 * */ int IsStackEmpty( StackList *s ) { return s->top == NULL; } /** * 进栈 * */ void Push( StackList *s, int data ) { //将新元素插入栈的头部 StackNode *pNode = ( StackNode * )malloc( sizeof( StackNode ) ); pNode->data = data; pNode->next = s->top; s->top = pNode; } /** * 出栈 * */ int Pop( StackList *s ) { int x; StackNode *pNode = s->top; //保存栈顶指针 if( IsStackEmpty( s ) ) { printf( "Stack underflow" ); exit( 0 ); } x = pNode->data; //保存栈顶节点数据 s->top = pNode->next; //将栈顶指针下移一个位置 free( pNode ); //释放原栈顶空间 return x; } /** * 取栈顶元素 * */ int GetTopStack( StackList *s ) { if( IsStackEmpty( s ) ) { printf( "Stack is empty" ); exit( 0 ); } return s->top->data; } int main( void ) { StackList *s; int i; s = ( StackList * )malloc( sizeof( StackList ) ); InitStack( s ); //初始化栈 for( i = 0; i < NUM; i++ ) { Push( s, i*2+1 ); //入栈处理 } i = GetTopStack( s ); //获取栈顶数据 printf( "%d /n", i ); printf( "出栈数据:/n" ); while( !IsStackEmpty( s ) ) { i = Pop( s ); printf( "%d ", i ); } return 0; }