生活随笔
收集整理的這篇文章主要介紹了
C语言 数据结构 栈的数组实现 realloc函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
主題:棧的數組實現
功能:分別棧的入棧、彈棧、打印操作
提示:運行程序自動進入入棧操作,退出入棧,數組3個ctrl z,然后進入出棧操作,輸入非n的任意char字符,繼續出棧。輸入n結束出棧,整個程序結束。
代碼
rewind(stdin);刷新緩沖區
void push(Pstack pstack, int num)入棧
int pop(Pstack pstack)出棧
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
#define INCREASE 10
typedef struct
{int *base
;int *top
;int length
;
}Stack
, *Pstack
;
void initial(Pstack pstack
)
{pstack
->base
= NULL;pstack
->top
= NULL;pstack
->length
= 0;
}
void push(Pstack pstack
, int num
)
{if (pstack
->top
== NULL){pstack
->base
= (int*)realloc(pstack
->base
, sizeof(int));if (!pstack
->base
){printf("分配內存錯誤\n");system("pause");}else{pstack
->top
= pstack
->base
;*(pstack
->top
) = num
;pstack
->length
++;}}else{pstack
->base
= (int*)realloc(pstack
->base
, sizeof(int) * (pstack
->top
- pstack
->base
+ 2));if (!pstack
->base
){printf("分配內存錯誤\n");system("pause");}else{pstack
->top
= pstack
->base
+ pstack
->length
- 1;pstack
->top
++;*(pstack
->top
) = num
;pstack
->length
++;}}
}
int pop(Pstack pstack
)
{if (pstack
->length
== 0){printf("棧為空\n");return -1;}int popper
;popper
= *(pstack
->top
);pstack
->top
--;pstack
->length
--;return popper
;
}
void print(Pstack pstack
)
{int length
= pstack
->length
;printf("輸出:");for (int i
= 0; i
< length
; i
++){printf("%d ", *(pstack
->base
+ i
));}printf("\n");printf("top = %p\n", pstack
->top
);printf("base = %p\n", pstack
->base
);printf("length = %d\n", length
);
}int main()
{int num
;Stack stack
;Pstack pstack
= &stack
;initial(pstack
);printf("入棧:\n");while (scanf("%d", &num
) != EOF){push(pstack
, num
);print(pstack
);rewind(stdin);}printf("出棧:輸入y/n\n");char checker
;while (scanf("%c", &checker
) && checker
!= 'n'){printf("%d已出棧\n", pop(pstack
));print(pstack
);rewind(stdin);}system("pause");
}
總結
以上是生活随笔為你收集整理的C语言 数据结构 栈的数组实现 realloc函数的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。