今天所学内容如下:
预习了顺序栈的基本操作(初始化操作、进栈操作、退栈操作、读取栈顶元素的值、测试栈空否、测试栈满否、返回栈的长度)双栈程序、多栈共享同一栈空间使用的栈浮动技术、以及链式栈的基本操作。
以下是栈用于将数组逆置的程序:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 #define initSize 20 5 #define N 10 6 typedef int SElemType; 7 typedef struct 8 { 9 SElemType *elem; 10 int top,maxSize; 11 }SeqStack; 12 void InitStack(SeqStack *S) 13 { 14 (*S).elem=(SElemType *)malloc(initSize*sizeof(SElemType)); 15 if((*S).elem==NULL) 16 { 17 printf("存储分配失败!\n"); 18 exit(1); 19 } 20 (*S).maxSize=initSize; 21 (*S).top=-1; 22 } 23 int Push(SeqStack *S,SElemType x) 24 { 25 if((*S).top==(*S).maxSize-1) 26 { 27 return 0; 28 } 29 (*S).elem[++(*S).top]=x; 30 return 1; 31 } 32 int Pop(SeqStack *S,SElemType *x) 33 { 34 if((*S).top==-1) 35 { 36 return 0; 37 } 38 *x=(*S).elem[(*S).top--]; 39 return 1; 40 } 41 int GetTop(SeqStack *S,SElemType *x) 42 { 43 if((*S).top==-1) 44 { 45 return 0; 46 } 47 *x=(*S).elem[(*S).top]; 48 return 1; 49 } 50 int StackEmpty(SeqStack *S) 51 { 52 return (*S).top==-1; 53 } 54 int StackFull(SeqStack *S) 55 { 56 return (*S).top==(*S).maxSize; 57 } 58 int StackSize(SeqStack *S) 59 { 60 return (*S).top+1; 61 } 62 void Reverse(SElemType A[],int n) 63 { 64 SeqStack S; 65 InitStack(&S); 66 int i; 67 for(i=1;i<=n;i++) 68 { 69 Push(&S,A[i-1]); 70 } 71 i=0; 72 while(!StackEmpty(&S)) 73 { 74 Pop(&S,&A[i++]); 75 } 76 } 77 main() 78 { 79 srand(time(NULL)); 80 int A[N]; 81 for(int i=0;i<10;i++) 82 { 83 A[i]=rand()%10+1; 84 } 85 printf("数组A逆置前为:\n"); 86 for(int i=0;i<N;i++) 87 { 88 printf("%3d",A[i]); 89 } 90 Reverse(A,N); 91 printf("\n数组A逆置后为:\n"); 92 for(int i=0;i<N;i++) 93 { 94 printf("%3d",A[i]); 95 } 96 printf("\n"); 97 98 }
程序运行结果如下:
(以上程序源自书上)书上的代码在形参表中,以&打头的参数为引用参数(使用了C++语言的引用调用的参数传递)。所以如果想运行书上的C语言代码,需将&改 *,并判断它是几级指针。