Stack
typedefstruct{ int*Elem; intlength; intAlloc_length;} stack;voidStack_init (Stack &s) {s.length=0; S.alloc_length=4; S.elem=New int[S.alloc_length]; ASSERT (S.elem!=nullptr);}voidStack_dispose (Stack &s) { Delete[] s.elem;}voidStack_push (Stack &s,intkey) { if(S.length = =s.alloc_length) {S.alloc_length*=2; int*temp =S.elem; S.elem=New int[S.alloc_length]; ASSERT (S.elem!=nullptr); for(intI=0; i<s.length;i++) {S.elem[i]=Temp[i]; } Delete[] temp; } s.elem[s.length++] =key;}intStack_pop (Stack &s) {Assert (S.length>0); S.length--; returns.elem[s.length];}
Queue
typedefstruct{ int*Elem; intsize; intAlloc_length;} Queue;voidQueue_init (Queue &s) {S.size=0; S.alloc_length=4; S.elem=New int[s.alloc_length];}voidQueue_dispose (Queue &s) { Delete[] s.elem;}voidQueue_push (Queue &s,intkey) { if(S.size = =s.alloc_length) {S.alloc_length*=2; int*t =S.elem; S.elem=New int[S.alloc_length]; for(intI=0; i<s.size; i++) {S.elem[i]=T[i]; } Delete[] t; } s.elem[s.size++] =key;}intQueue_pop (Queue &s) {Assert (S.size>0); intKey = s.elem[0]; //S.elem = S.elem + 1; //can ' t do this way,if so,original S.elem would be a lost,then we can ' t use delete[] S.elem in Queue_dispose for(intI=0; i<s.size; i++) {S.elem[i]= s.elem[i+1];//When i=s.size-1,the last element would be ereased} s.size--; returnkey;}
Duplicate items and index entries
Suppress duplicates:
- Old items Forgotten
- New Item ignored
Exception: The elements of the stack are integers.
typedefstruct{ int*elem;//Store Elements int*index;//Tell if a certain an element in stack intsize; intAlloc_size;} Stack;//new item ignored, easyvoidStack_push (Stack &s,intkey) { if(S.elem[key] = =1){ return; } s.elem[s.size++] =key; S.index[key]=1;}//old items ForgottenvoidStack_push (Stack &s,intkey) { if(S.elem[key] = =1) {look_delete (S,key); S.elem[s.size]=key; } s.elem[s.size++] =key; S.index[key]=1;}
Stack and Queue