00001
00009 #include <stdlib.h>
00010 #include "stack.h"
00011
00012
00013 Stack newStack()
00014 {
00015 Stack stack=(Stack)malloc(sizeof(SStack));
00016
00017 if(!stack) return NULL;
00018 else
00019 {
00020 stack->size=0;
00021 stack->top=NULL;
00022 return stack;
00023 }
00024 }
00025
00026
00027
00028 void stackDelete(Stack stack)
00029 {
00030 StackNode aux1,aux2;
00031
00032 if(stack->size) free(stack);
00033 else
00034 {
00035 for(aux1=stack->top;aux1;)
00036 {
00037 aux2=aux1;
00038 aux1=aux1->next;
00039 free(aux2);
00040 }
00041 free(stack);
00042 }
00043 }
00044
00045
00046
00047 int stackPush(Stack stack,void *inf)
00048 {
00049 StackNode new;
00050
00051 new=(StackNode)malloc(sizeof(SStackNode));
00052
00053 if(new)
00054 {
00055 stack->size++;
00056 new->inf=inf;
00057 new->next=stack->top;
00058 stack->top=new;
00059
00060 return 0;
00061 }
00062 else return 1;
00063 }
00064
00065
00066
00067 int stackPop(Stack stack,void **inf)
00068 {
00069 StackNode aux;
00070
00071 if(!stack->size)
00072 {
00073 if(inf) *inf=NULL;
00074 return 1;
00075 }
00076 else
00077 {
00078 if(inf) *inf=stack->top->inf;
00079 aux=stack->top;
00080 stack->top=stack->top->next;
00081 free(aux);
00082 stack->size--;
00083
00084 return 0;
00085 }
00086 }
00087
00088
00089
00090 int stackTop(Stack stack,void **inf)
00091 {
00092 if(!stack->size)
00093 {
00094 *inf=NULL;
00095 return 1;
00096 }
00097 else
00098 {
00099 *inf=stack->top->inf;
00100 return 0;
00101 }
00102 }
00103
00104
00105
00106 int stackSize(Stack stack)
00107 {
00108 return(stack->size);
00109 }
00110
00111
00112
00113 int stackMap(Stack stack,void(*fun)(void*))
00114 {
00115 StackNode aux;
00116
00117 if(!stack->size) return 1;
00118 else
00119 {
00120 for(aux=stack->top;aux;aux=aux->next)
00121 fun(aux->inf);
00122
00123 return 0;
00124 }
00125 }
00126
00127
00128
00129 Iterator stackIterator(Stack stack)
00130 {
00131 int ctrl;
00132 StackNode aux;
00133 Iterator it;
00134
00135 it=newIt(stack->size);
00136 for(aux=stack->top,ctrl=0;aux&&!ctrl;aux=aux->next)
00137 ctrl=itAdd(it,aux->inf);
00138
00139 if(ctrl)
00140 {
00141 itDelete(it);
00142 return NULL;
00143 }
00144 else return it;
00145 }