c言語について質問です。スタックに関するいろいろな関数を書いているのですが、スタックの先頭を複製する関数とスタックの先頭を削除する関数が分かりません。
c言語について質問です。スタックに関するいろいろな関数を書いているのですが、スタックの先頭を複製する関数とスタックの先頭を削除する関数が分かりません。 void dup と void dropです。 ソースです。 (略) #define STACKSIZE 100 struct stack { int top; int val[STACKSIZE]; }; void push(struct stack *st, int data); void print(struct stack *st); int top(struct stack *st); void init(struct stack *st); void dup(struct stack *st); void swap(struct stack *st); void drop(struct stack *st); int main(void){ int i, tmp; struct stack st; init(&st); for(i = 0; i < 5; i++) { printf("Input number:"); scanf("%d", &tmp); push(&st, tmp); printf("\n"); } print(&st); dup(&st); print(&st); drop(&st); drop(&st); print(&st); printf("top:%d\n", top(&st)); swap(&st); print(&st); printf("top:%d\n", top(&st)); return 0; } void push(struct stack *st, int data){ if (st->top == STACKSIZE -1) { printf("Error: stack is full\n"); exit(1); } else { st->top++; st->val[st->top] = data; } } int pop(struct stack *st) { if (st->top == -1) { printf("Error: stack is empty\n"); exit(1); } else { int a = st->top; st->top--; return st->val[a]; } } void print(struct stack *st){ int i; for (i = 0; i < 5; i++){ printf("%d ",st->val[i]); } printf("\n"); } int top(struct stack *st){ if(st->top == -1){ printf("Error: stack is empty\n"); exit(1); } else{ return st->val[st->top]; } } void init(struct stack *st){ int i; for(i = 0; i < STACKSIZE; i++){ st->val[i] = 0; } st->top = -1; } void dup(struct stack *st){ int a; a = st->val[st->top]; st->top++; st->val[st->top] = a; } void swap(struct stack *st){ int b = st->val[st->top]; st->val[st->top] = st->val[st->top - 1]; st->val[st->top - 1] = b; } void drop(struct stack *st){ st->top--; }
C言語関連・98閲覧
ベストアンサー
(1150460916さん) int top(struct stack *st); ↑ topってpopのことかな? ●先頭を複製する関数 dup popしてその値を2回 push すればいい ●スタックの先頭を削除する関数 drop popしてその値を捨てればいい
void dup(struct stack *st){ int v; v=pop(st); push(st,v); push(st,v); } void drop(struct stack *st){ pop(st); }
質問者からのお礼コメント
ありがとうございます。
お礼日時:5/19 1:43