| 1 | /* $Id$Revision: */ |
| 2 | /* vim:set shiftwidth=4 ts=8: */ |
| 3 | |
| 4 | /************************************************************************* |
| 5 | * Copyright (c) 2011 AT&T Intellectual Property |
| 6 | * All rights reserved. This program and the accompanying materials |
| 7 | * are made available under the terms of the Eclipse Public License v1.0 |
| 8 | * which accompanies this distribution, and is available at |
| 9 | * http://www.eclipse.org/legal/epl-v10.html |
| 10 | * |
| 11 | * Contributors: See CVS logs. Details at http://www.graphviz.org/ |
| 12 | *************************************************************************/ |
| 13 | |
| 14 | #include "general.h" |
| 15 | #include "IntStack.h" |
| 16 | |
| 17 | IntStack IntStack_new(void){ |
| 18 | IntStack s; |
| 19 | int max_len = 1<<5; |
| 20 | |
| 21 | s = MALLOC(sizeof(struct IntStack_struct)); |
| 22 | s->max_len = max_len; |
| 23 | s->last = -1; |
| 24 | s->stack = MALLOC(sizeof(int)*max_len); |
| 25 | return s; |
| 26 | } |
| 27 | |
| 28 | void IntStack_delete(IntStack s){ |
| 29 | if (s){ |
| 30 | FREE(s->stack); |
| 31 | FREE(s); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | static IntStack IntStack_realloc(IntStack s){ |
| 36 | int max_len = s->max_len; |
| 37 | |
| 38 | max_len = max_len + MAX(10,0.2*max_len); |
| 39 | s->max_len = max_len; |
| 40 | s->stack = REALLOC(s->stack, sizeof(int)*max_len); |
| 41 | if (!s->stack) return NULL; |
| 42 | return s; |
| 43 | } |
| 44 | |
| 45 | int IntStack_push(IntStack s, int i){ |
| 46 | /* add an item and return the pos. Return negative value of malloc failed */ |
| 47 | if (s->last >= s->max_len - 1){ |
| 48 | if (!(IntStack_realloc(s))) return -1; |
| 49 | } |
| 50 | s->stack[++(s->last)] = i; |
| 51 | return s->last; |
| 52 | } |
| 53 | int IntStack_pop(IntStack s, int *flag){ |
| 54 | /* remove the last item. If none exist, return -1 */ |
| 55 | *flag = 0; |
| 56 | if (s->last < 0){ |
| 57 | *flag = -1; |
| 58 | return -1; |
| 59 | } |
| 60 | return s->stack[(s->last)--]; |
| 61 | } |
| 62 | void IntStack_print(IntStack s){ |
| 63 | /* remove the last item. If none exist, return -1 */ |
| 64 | int i; |
| 65 | for (i = 0; i <= s->last; i++) fprintf(stderr,"%d," ,s->stack[i]); |
| 66 | fprintf(stderr,"\n" ); |
| 67 | } |
| 68 | |
| 69 | /* |
| 70 | main(){ |
| 71 | |
| 72 | IntStack s; |
| 73 | int i, len = 1, pos, flag; |
| 74 | |
| 75 | for (;;){ |
| 76 | s = IntStack_new(); |
| 77 | fprintf(stderr,"=============== stack with %d elements ============\n",len); |
| 78 | for (i = 0; i < len; i++){ |
| 79 | pos = IntStack_push(s, i); |
| 80 | if (pos < 0){ |
| 81 | fprintf(stderr," fail to push element %d, quit\n", i); |
| 82 | exit(1); |
| 83 | } |
| 84 | } |
| 85 | for (i = 0; i < len+1; i++){ |
| 86 | IntStack_pop(s, &flag); |
| 87 | if (flag) { |
| 88 | fprintf(stderr, "no more element\n"); |
| 89 | } |
| 90 | } |
| 91 | IntStack_delete(s); |
| 92 | len *= 2; |
| 93 | } |
| 94 | } |
| 95 | */ |
| 96 | |