main2.c (2825B)
1 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 struct StackItem_; 6 7 typedef struct StackItem_ { 8 char value; 9 struct StackItem_ *next, *prev; 10 } StackItem; 11 12 typedef struct Stack_ { 13 StackItem *top, *bottom; 14 } Stack; 15 16 void push_top(Stack *stack, StackItem *item) { 17 if (stack->top) 18 { 19 StackItem* old = stack->top; 20 old->next = item; 21 item->prev = old; 22 } 23 if (!stack->top) stack->bottom = item; 24 stack->top = item; 25 } 26 27 void push_back(Stack *stack, StackItem *item) { 28 if (stack->bottom) 29 { 30 StackItem* old = stack->bottom; 31 old->prev = item; 32 item->next = old; 33 } 34 if (!stack->bottom) stack->top = item; 35 stack->bottom = item; 36 } 37 38 StackItem* pop_top(Stack *stack) { 39 StackItem* old = stack->top; 40 stack->top = old->prev; 41 if (old->prev != 0) 42 { 43 stack->top->next = 0; 44 } 45 old->next = old->prev = 0; 46 47 return old; 48 } 49 50 StackItem* pop_back(Stack *stack) { 51 StackItem* old = stack->bottom; 52 stack->bottom = old->next; 53 stack->bottom->prev = 0; 54 old->next = old->prev = 0; 55 56 return old; 57 } 58 59 void printCargo(Stack *cargo, size_t len) 60 { 61 for (int i = 0; i < len; i++) 62 { 63 for ( StackItem *e = cargo[i].bottom; e != 0; e = e->next ) 64 { 65 printf("%c", e->value); 66 } 67 printf("\n"); 68 } 69 } 70 71 int main() 72 { 73 char *line = 0; 74 size_t len; 75 Stack *cargo; 76 size_t cargos; 77 ssize_t nread; 78 79 int amount, from, to; 80 81 Stack *temp = malloc(sizeof(Stack)); 82 83 while ((nread = getline(&line, &len, stdin)) != 0) 84 { 85 if ( line[1] == '1' ) continue; 86 if ( line[0] == '\n' ) break; 87 if ( !cargo ) { 88 cargos = (nread+1)/4; 89 cargo = (Stack*)malloc( sizeof(Stack) * cargos ); 90 } 91 92 for (int i = 0; i < cargos; i++ ) { 93 char load = line[i*4+1]; 94 if ( load != ' ' ) { 95 StackItem *box = malloc(sizeof(StackItem)); 96 box->value = line[i*4+1]; 97 box->next = box->prev = 0; 98 push_back(&cargo[i], box); 99 } 100 } 101 } 102 103 printCargo(cargo, cargos); 104 printf("---------------\n"); 105 106 while (scanf("move %d from %d to %d\n", &amount, &from, &to) != EOF) 107 { 108 printf( "%d %d %d\n", amount, from, to ); 109 for (int i = 0; i < amount; i++) 110 { 111 StackItem *item = pop_top(&cargo[from-1]); 112 push_top(temp, item); 113 } 114 for (int i = 0; i < amount; i++) 115 { 116 StackItem *item = pop_top(temp); 117 push_top(&cargo[to-1], item); 118 119 printCargo(cargo, cargos); 120 printf("---------------\n"); 121 } 122 } 123 124 for ( int i = 0; i < cargos; i++ ) 125 { 126 printf( "%c", cargo[i].top->value ); 127 } 128 printf("\n"); 129 }