学习日记一:顺序栈的操作集
一开始写错,调用IsEmpty,IsFull函数竟然没写实参建立栈时竟然忘记建立空间保存栈这种结构
程序代码:
#include <stdio.h> #define MaxSize 100 struct StackNode { int data[MaxSize]; int top; }; typedef struct StackNode *PtrStackNode; PtrStackNode create( int N ) { void PushStack( stack );//要函数声明,否则将PushStack看成int返回值类型,造成类型不匹配 PtrStackNode stack; int i; stack->top=-1; for( i=0 ; i<N ; i++ ) { PushStack( stack ); } return stack; } int IsEmpty( PtrStackNode stack ) { if( stack->top==-1 ) return 1; else return 0; } int IsFull( PtrStackNode stack ) { if( stack->top == MaxSize-1 ) return 1; else return 0; } void PushStack( PtrStackNode stack ) { int item; if( !IsFull ) { scanf("%d",&item); stack->top++; stack->data[stack->top] = item ; return; } else { printf("栈已满\n"); return; } } void PopStack( PtrStackNode stack ) { if(IsEmpty) printf("栈已空,无法出栈\n"); //有返回值的函数无返回 else printf ( "已删除%d\n" , stack->data[stack->top--] ) ; //如果是stack->top减2,可以将其赋值给一个变量,减2后再返回 } void OutPutStack(PtrStackNode stack) { int k; k=stack->top; while(k>-1) { printf( "%d\n" , stack->data[k] ); k--; } printf("已输出完毕\n") ; return; } int main() { int N; PtrStackNode stack; printf("请输入栈中元素个数:"); scanf("%d",&N); printf("\n"); stack = create( N ) ; //建栈N个元素,返回栈结点指针 OutPutStack(stack); PopStack(stack); OutPutStack(stack); PushStack(stack); }
修改之后
程序代码:
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 struct StackNode { int data[MaxSize]; int top; }; typedef struct StackNode *PtrStackNode; void PushStack( PtrStackNode stack ); PtrStackNode create( int N ) { void PushStack( PtrStackNode stack );//要函数声明,否则将PushStack看成int返回值类型,造成类型不匹配 PtrStackNode stack = (PtrStackNode) malloc( sizeof (struct StackNode) ) ;//建立栈时需要开辟一个空间让指针指向它,在空间内有元素data数组 int i; stack->top=-1; for( i=0 ; i<N ; i++ ) { PushStack( stack ); } return stack; } int IsEmpty( PtrStackNode stack ) { if( stack->top==-1 ) return 1; else return 0; } int IsFull( PtrStackNode stack ) { if( stack->top == MaxSize-1 ) return 1; else return 0; } void PushStack( PtrStackNode stack ) { int item; if( !IsFull(stack) ) { scanf("%d",&item); stack->top++; stack->data[stack->top] = item ; return; } else { printf("栈已满\n"); return; } } void PopStack( PtrStackNode stack ) { if(IsEmpty(stack)) printf("栈已空,无法出栈\n"); //有返回值的函数无返回 else printf ( "已删除%d\n" , stack->data[stack->top--] ) ; //如果是stack->top减2,可以将其赋值给一个变量,减2后再返回 } void PrintfPutStack(PtrStackNode stack) { int k; k=stack->top; while(k>-1) { printf( "%d\n" , stack->data[k] ); k--; } printf("已输出完毕\n") ; return; } int main() { int N; PtrStackNode stack; printf("请输入栈中元素个数:"); scanf("%d",&N); printf("\n"); stack = create( N ) ; //建栈N个元素,返回栈结点指针 PrintfPutStack(stack); PopStack(stack); PrintfPutStack(stack); PushStack(stack); }