cでのスタック構造のポップのやり方が
プログラミングを始めたばかりでよくわからないです。
よろしくお願いします。
c
1#include<stdio.h> 2#include<stdlib.h> 3 4typedef struct _cell{ 5 int i; 6 struct _cell *next; 7}cell; 8 9typedef struct _stack{ 10 cell *head; 11}stack; 12 13/*スタックを生成する関数*/ 14stack* create(){ 15 stack *S = (stack *)malloc(sizeof(stack)); 16 S -> head = (cell *)malloc(sizeof(cell));/*ダミーセル*/ 17 S -> head -> next = NULL; 18 S -> head -> i = -1; 19 return S; 20} 21 22/*push*/ 23void push(stack *S,int i){ 24 cell *push = (cell *)malloc(sizeof(cell)); 25 push->i = i; 26 push->next = S->head->next; 27 S->head->next = push; 28} 29 30/*pop*/ 31int pop(){ /*ここのポップができない*/ 32 int i; 33 stack *S; 34 S = head->next; 35 head->next = S->next; 36 i = S->i; 37 free(S); 38 return i; 39} 40 41/*スタックの中身を表示する関数*/ 42void print(stack *S){ 43 cell *ptr = S->head->next;/*ダミーセルをスキップ*/ 44 while(ptr != NULL){ 45 printf("%d ",ptr->i); 46 ptr = ptr->next; 47 } 48 printf("\n"); 49} 50 51 52int main (){ 53 stack *S = create(); 54 55 push(S,5); 56 push(S,3); 57 push(S,6); 58 pop(S); 59 push(S,3); 60 push(S,7); 61 pop(S); 62 print(S); 63 64 return 0; 65} 66 67 68
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。