求一个用C语言写的关于栈的基本操作的代码。
要用链栈,顺序栈我会的,谢谢。。(不是交作业用的哟,是自己要找一段代码弄懂什么是链栈),谢谢。。
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef int elem_type; 5 typedef struct _stack 6 { 7 elem_type elem; 8 struct _stack *next; 9 }stack, *pstack; 10 11 int is_empty(pstack nstack) 12 { 13 if (NULL == nstack) 14 { 15 return 0; 16 } 17 18 return -1; 19 } 20 21 pstack get_top(pstack nstack) 22 { 23 if (0 == is_empty(nstack)) 24 { 25 //print msg error 26 return NULL; 27 } 28 29 return nstack; 30 } 31 32 int pop(pstack *nstack) 33 { 34 if (0 == is_empty(*nstack)) 35 { 36 //print msg error 37 return -1;//failed 38 } 39 pstack ntmp = *nstack; 40 *nstack = (*nstack)->next; 41 free(ntmp); ntmp = NULL; 42 43 return 0;//success 44 } 45 46 int push(pstack *nstack, elem_type nelem) 47 { 48 pstack ntmp = (pstack) malloc (sizeof(stack)); 49 50 if (NULL == ntmp) 51 { 52 return -1;//failed 53 } 54 55 ntmp->elem = nelem; 56 ntmp->next = *nstack; 57 *nstack = ntmp; 58 59 return 0;//success 60 } 61 62 int main(void) 63 { 64 pstack nstack=NULL, ntmp; 65 int i; 66 67 for (i=0; i<10; ++i) 68 { 69 push(&nstack, i); 70 } 71 72 while (0 != is_empty(nstack)) 73 { 74 ntmp = get_top(nstack); 75 printf ("%d\n", ntmp->elem); 76 pop(&nstack); 77 } 78 79 return 0; 80 }