棧是一種先進后出的數(shù)據(jù)結(jié)構(gòu),計算機中常見的函數(shù)調(diào)用就用到了這種結(jié)構(gòu),其常用的操作就是出棧、入棧,如下圖,數(shù)據(jù)總是從棧頂入,從棧頂出:
創(chuàng)新互聯(lián)建站專注于官渡網(wǎng)站建設(shè)服務及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供官渡營銷型網(wǎng)站建設(shè),官渡網(wǎng)站制作、官渡網(wǎng)頁設(shè)計、官渡網(wǎng)站官網(wǎng)定制、微信小程序定制開發(fā)服務,打造官渡網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供官渡網(wǎng)站排名全網(wǎng)營銷落地服務。

接下來看一個簡單的程序?qū)础癮bcdef”入棧,并打印其出棧順序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_SIZE 16
#define NAME_MAX_SIZE 32
#define ERR -1
#define SUCC 0
typedef struct stack {
char *array; /* 棧的起始地址 */
int stack_size; /* 棧大小 */
int top; /* 棧頂所在的位置 */
char(*pop)(struct stack *sta); /* 出棧 */
int (*push)(struct stack *sta, char data); /* 入棧 */
} stack_t;
static int is_empty(stack_t *sta)
{
return (sta->top == -1);
}
static int is_full(stack_t *sta)
{
return (sta->top == sta->stack_size-1);
}
/* 將棧頂元素出棧,并返回 */
char pop_stack(stack_t *sta)
{
char ch;
if (is_empty(sta)) {
printf("the stack is empty \n");
return ERR;
}
ch = sta->array[sta->top];
--sta->top;
return ch;
}
/* 在棧頂插入元素 */
int push_stack(stack_t *sta, char data)
{
if (is_full(sta)) {
printf("the stack is full \n");
return ERR;
}
++sta->top;
sta->array[sta->top] = data;
return SUCC;
}
void init_stack(stack_t **sta)
{
*sta = (stack_t *)malloc(sizeof(stack_t));
if ((*sta) == NULL) {
printf("no mem \n");
return ;
}
(*sta)->top = -1;
(*sta)->stack_size = STACK_SIZE;
(*sta)->pop = pop_stack;
(*sta)->push = push_stack;
(*sta)->array = (char *)malloc(STACK_SIZE);
if ((*sta)->array == NULL) {
printf("no mem \n");
return ;
}
}
int main(int argc, char *argv[])
{
int size, ret, i;
stack_t *sta_addr;
char data[] = "abcdef";
init_stack(&sta_addr);
size = sizeof(data) / sizeof(data[0]);
for (i = 0; i < size; i++) {
sta_addr->push(sta_addr, data[i]);
}
while (1) {
ret = sta_addr->pop(sta_addr);
if (ret != ERR) {
printf("%c,", ret);
} else {
break;
}
}
return 0;
}
新聞名稱:數(shù)據(jù)結(jié)構(gòu)之棧c語言實現(xiàn)
瀏覽地址:http://www.chinadenli.net/article2/piejoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈、小程序開發(fā)、靜態(tài)網(wǎng)站、網(wǎng)站建設(shè)、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)