The first part of this question is easy: use a set of stacks to mimic a single stack. In the second part, we need to implement a new method as popAt(int index) to make a pop operation on a specific sub-stack. In our solution, we deploy a lazy-defragment method. We allow some sub-stacks not being full after calling popAt. And only when more free space is need (in push operation), we try defragment to eliminate fragment inside each sub-stacks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | /*============================================================================= # Author: Sheng Yu - https://34.145.67.234 # Email : yusheng123 at gmail dot com # Last modified: 2013-10-11 00:54 # Filename: 3.3.c # Description: implement a SetofStacks to use multi-stacks in an easy way =============================================================================*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <errno.h> // Configuration Section // For total_stacks, we could do it better. Yes, we CAN #define TOTAL_STACKS 4 const int RAW_INPUT_MAX_LEN = 20; const size_t SINGLE_STACK_SIZE = 4; // The definition of stack struct simple_stack{ int *bottom; int *top; int capacity; }; struct SetofStacks{ struct simple_stack *stacks[TOTAL_STACKS]; int current; int capacity; }; // Functions to operate on the simple_stack bool simple_init(struct simple_stack *stack); bool simple_push(struct simple_stack *stack, int value); int simple_pop(struct simple_stack *stack); int simple_peek(struct simple_stack stack); void simple_print_stack(struct simple_stack stack); bool simple_isfull(struct simple_stack stack); bool simple_isempty(struct simple_stack stack); void simple_clean(struct simple_stack *stack); // Functions to operate on the SetofStacks bool set_init(struct SetofStacks *stackset); bool set_push(struct SetofStacks *stackset, int value); int set_pop(struct SetofStacks *stackset); int set_popAt(struct SetofStacks *stackset, int stack_index); int set_peek(struct SetofStacks stackset); void set_print_stack(struct SetofStacks stackset); bool set_isfull(struct SetofStacks stackset); bool set_isempty(struct SetofStacks stackset); void set_clean(struct SetofStacks *stackset); // Functions to build the interactive test interface void shell_usage(char *input); int stack_shell(); // Function implementation bool simple_init(struct simple_stack *stack){ // prepare the stack for use, majorly allocate the memory stack->bottom = (int *)malloc(SINGLE_STACK_SIZE * sizeof(int)); stack->top = stack->bottom; if( stack->bottom == NULL ){ // if the memroy allocation fails stack->capacity = 0; return false; } else{ memset(stack->bottom, 0, SINGLE_STACK_SIZE * sizeof(int)); stack->capacity = SINGLE_STACK_SIZE; return true; } } bool simple_push(struct simple_stack *stack, int value){ if( stack->top - stack->bottom >= stack->capacity){ return false; // full } else{ *(stack->top++) = value; return true; } } int simple_pop(struct simple_stack *stack){ if( stack->top - stack->bottom == 0){ errno = ENODATA; return 0; // empty } else{ return *(--stack->top); } } int simple_peek(struct simple_stack stack){ if( stack.top - stack.bottom == 0){ errno = ENODATA; return 0; // empty } else{ return *(stack.top-1); } } void simple_print_stack(struct simple_stack stack){ int *current = NULL; if(stack.top == stack.bottom){ printf("The stack is EMPTY.n"); } else{ current = stack.bottom; printf("It is (from bottom to top): %d", *(current++)); while(current != stack.top){ printf(" -> %d", *current); ++current; } printf("n"); } return; } bool simple_isfull(struct simple_stack stack){ return (stack.top-stack.bottom) == stack.capacity; } bool simple_isempty(struct simple_stack stack){ return stack.top==stack.bottom; } void simple_clean(struct simple_stack *stack){ free(stack->bottom); stack->top = stack->bottom = NULL; stack->capacity = 0; return; } bool set_init(struct SetofStacks *stackset){ int stack_index = 0; // prepare the stack set stackset->current = 0; memset(stackset->stacks, 0, sizeof(struct simple_stack *)*TOTAL_STACKS); for(stack_index=0; stack_index<TOTAL_STACKS; ++stack_index){ // initialize each sub-stack (stackset->stacks)[stack_index] = (struct simple_stack *)malloc( sizeof(struct simple_stack)); if( (stackset->stacks)[stack_index] != NULL && !simple_init((stackset->stacks)[stack_index])){ // fail to initialize this sub-stack, roll back and exit if( (stackset->stacks)[stack_index] != NULL ){ // no need to clean the sub-stack free((stackset->stacks)[stack_index]); } --stack_index; for(; stack_index >= 0; --stack_index){ simple_clean((stackset->stacks)[stack_index]); free((stackset->stacks)[stack_index]); } return false; } } stackset->capacity = TOTAL_STACKS; return true; } bool set_push(struct SetofStacks *stackset, int value){ struct simple_stack temp; int temp_val = 0; int read_index = 0, write_index = 0; // find a sub-stack with free space, from current to last while( stackset->current < stackset->capacity){ if( !simple_push( stackset->stacks[stackset->current], value) ){ // current using sub-stack is full // switch to the next sub-stack ++(stackset->current); } else{ // free space available, and push successfully return true; } } // Adjust the current --stackset->current; // Seems all the stackset is full. Try defragment // We deploy a lazy method. Only when we need more space, // we try to defrag. if( !simple_init(&temp) ){ // fail to initialize the temp simple stack return false; } write_index = 0; // would never greater than read_index for(read_index = 0; read_index<stackset->capacity; ++read_index){ // read the whole data in one sub-stack errno = 0; temp_val = simple_pop(stackset->stacks[read_index]); while(errno != ENODATA){ simple_push(&temp, temp_val); // definitely enough space temp_val = simple_pop( (stackset->stacks)[read_index] ); } // write the data back to the stackset errno = 0; temp_val = simple_pop(&temp); while( errno != ENODATA){ if( !simple_push(stackset->stacks[write_index], temp_val)){ // current writting sub-stack is full // switch to the next one // since we read all data out, and then write back // the next one sub-stack must be empty ++write_index; simple_push(stackset->stacks[write_index], temp_val); } temp_val = simple_pop(&temp); } } simple_clean(&temp); // adjust the current of stackset stackset->current = write_index; // after defragment, try to find a free space again. while( stackset->current < stackset->capacity){ if( !simple_push( stackset->stacks[stackset->current], value) ){ // current using sub-stack is full // switch to the next sub-stack ++(stackset->current); } else{ // free space available, and push successfully return true; } } // really full... adjust the current value, and return --stackset->current; return false; } int set_popAt(struct SetofStacks *stackset, int stack_index){ // Check the index for the sub-stack if(stack_index < 0 || stack_index >= stackset->capacity){ errno = ERANGE; return -1; // return value does not matter } // Try to pop from the specific sub-stack errno = 0; return simple_pop( (stackset->stacks)[stack_index] ); } int set_pop(struct SetofStacks *stackset){ int ret = 0; // Try to pop from the last sub-stack to the first one while(stackset->current >= 0){ errno = 0; ret = simple_pop( (stackset->stacks)[stackset->current] ); if( errno == ENODATA ){ --(stackset->current); // might become -1 } else{ return ret; } } // Adjust the current position if( stackset->current < 0 ){ stackset->current = 0; } errno = ENODATA; return -1; // return value does not matter, empty } int set_peek(struct SetofStacks stackset){ int ret = 0; // Try to pop from the last sub-stack to the first one while(stackset.current >= 0){ errno = 0; ret = simple_peek( *((stackset.stacks)[stackset.current]) ); if( errno == ENODATA ){ --(stackset.current); // might become -1 } else{ return ret; } } // No need to adjust the current position, these changes do not // take effect outsaide errno = ENODATA; return -1; // return value does not matter, empty } void set_print_stack(struct SetofStacks stackset){ int current = 0; // Print out hte information about the stack set in a human // friendly manner printf("The stacks set has %d stack%s.n", stackset.capacity, stackset.capacity == 1 ? "" : "s"); printf("Each sub-stack can store %d integers.n", stackset.stacks[0]->capacity); printf("The sub-stack in use is #%d.n", stackset.current); printf("The contents in stacks are:n"); while(current < stackset.capacity){ printf("t#%d: ", current); simple_print_stack(*(stackset.stacks[current])); ++current; } return; } bool set_isfull(struct SetofStacks stackset){ int check_pos = 0; for(check_pos=0; check_pos < stackset.capacity; ++check_pos){ if( !simple_isfull(*(stackset.stacks[check_pos])) ){ return false; } } return true; } bool set_isempty(struct SetofStacks stackset){ int check_pos = 0; for(check_pos=0; check_pos < stackset.capacity; ++check_pos){ if( !simple_isempty(*(stackset.stacks[check_pos])) ){ return false; } } return true; } void set_clean(struct SetofStacks *stackset){ // Destructor int clean_pos = 0; for(clean_pos = 0; clean_pos < stackset->capacity; ++clean_pos){ simple_clean((stackset->stacks)[clean_pos]); free((stackset->stacks)[clean_pos]); (stackset->stacks)[clean_pos] = NULL; } stackset->current = 0; stackset->capacity = 0; return; } void shell_usage(char *input){ char *in[] = {"help popn", "help pushn", "help peekn", "help exitn", "help quitn", "help printn", "help popAtn", "help isfulln","help isemptyn"}; char *help[] = {"pop: popn", "push: push integern", "peek: peekn", "exit: same with quit. Quit this program.n", "quit: quit this program.n", "print: printn", "popAt: popAt integern", "isfull: isfulln", "isempty: isemptyn", "Command list: pop, push, peek, print, popAt, exit, " "quit, isfull, isempty.nUse "help command" " "for more details.n"}; int index = -1; while( ++index < sizeof(in)/sizeof(char *) && strcmp(input, in[index]) != 0 ); printf("%s",help[index]); return; } int stack_shell(){ // A simple interactive shell to test the stack // operation functions. // some variables to store the user's input char raw_in[RAW_INPUT_MAX_LEN]; char temp[RAW_INPUT_MAX_LEN]; bool skip = false; // the core part: the stack set struct SetofStacks StackSet = { .current = 0, .capacity = 0 }; // Some variables to manipulate the stack set int push_value = -1; int ret_value = 0; int set_index = 0; // Prepare the stack set if( !set_init(&StackSet)){ // fail to initialize the stackset printf("Fail to set up the working environment.n"); return -1; } // recive commands do{ if(!skip){ printf("Stack Shell>> "); } fgets( raw_in, RAW_INPUT_MAX_LEN, stdin); if ( raw_in[strlen(raw_in)-1] != 'n' ){ // The input is longer than RAW_INPUT_MAX_LEN // The left part should be ignored. skip = true; } else if( skip ){ // This is the latter part of a too-long input // It should be ignored. printf("Unknown command! "); printf("Use "help" to read usage.n"); skip = false; } else{ // Amalyze the input if( strcmp(raw_in, "isfulln") == 0 ){ printf("The stack set is%s full.n", set_isfull(StackSet) ? "" : " not"); } else if( strcmp(raw_in, "isemptyn") == 0 ){ printf("The stack set is%s empty.n", set_isempty(StackSet) ? "" : " not"); } else if( strncmp(raw_in, "popAt", 5) == 0 ){ // we MUST check popAT before pop if( sscanf(raw_in,"popAt%*[ ]%d%s", &set_index, temp) != 1 ){ printf("Improper command: %s", raw_in); printf("Example: popAt 1n"); } else{ errno = 0; ret_value = set_popAt(&StackSet, set_index); if(errno == ENODATA){ printf("The sub-stack is empty.n"); } else if(errno == ERANGE){ printf("The index %d is out of range [ 0, %d)", set_index, StackSet.capacity); } else{ printf("The top item in #%d sub-stack is: %dn", set_index, ret_value); } } } else if( strncmp(raw_in, "pop", 3) == 0 ){ if( sscanf(raw_in,"pop%s", temp) != EOF ){ printf("Improper command: %s", raw_in); printf("Example: popn"); } else{ errno = 0; ret_value = set_pop(&StackSet); if( errno == ENODATA){ printf("The stack was empty.n"); } else{ printf("Pop from stack is: %dn",ret_value); } } } else if( strncmp(raw_in, "push", 4) == 0 ){ if( sscanf(raw_in,"push%*[ ]%d%s", &push_value,temp) != 1){ printf("Improper command: %s", raw_in); printf("Usage: push valuen"); printf("Example: push 99n"); } else{ if( set_push(&StackSet, push_value) ){ printf("Push successfully: %dn", push_value); } else{ printf("Fail to push: the set of stacks is full.n"); } } } else if( strncmp(raw_in, "peek", 4) == 0 ){ if( sscanf(raw_in,"peek%s",temp) != EOF ){ printf("Improper command: %s", raw_in); printf("Example: peekn"); } else{ errno = 0; ret_value = set_peek(StackSet); if( errno == ENODATA ){ printf("The stack was empty.n"); } else{ printf("The top item in stack is: %dn", ret_value); } } } else if( strncmp(raw_in, "print", 5) == 0 ){ if( sscanf(raw_in,"print%s", temp) != EOF ){ printf("Improper command: %s", raw_in); printf("Example: printn"); } else{ set_print_stack(StackSet); } } else if( strncmp(raw_in, "exitn", 5) == 0 ){ break; } else if( strncmp(raw_in, "quitn", 5) == 0 ){ break; } else if( strncmp(raw_in, "help", 4) == 0 ){ shell_usage(raw_in); } else{ printf("Unknown command: %.*s. ", (int)strlen(raw_in)-1, raw_in); printf("Use "help" to read usage.n"); } } } while(!feof(stdin) && !ferror(stdin)); set_clean(&StackSet); return 0; } int main(int argc, char *argv[]){ // Check the arguments if(argc != 1){ printf("Usage: %sn",argv[0]); return -1; } return stack_shell(); } |