兩棧共用空間的C語言實現

來源:互聯網
上載者:User

標籤:printf   實現   while   c語言實現   若是   分配   mat   一個   tac   

#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 儲存空間初始分配量 */

typedef int Status;

typedef int SElemType; /* SElemType類型根據實際情況而定,這裡假設為int */


/* 兩棧共用空間結構 */
typedef struct
{
SElemType data[MAXSIZE];
int top1;/* 棧1棧頂指標 */
int top2;/* 棧2棧頂指標 */
}SqDoubleStack;


Status visit(SElemType c)
{
printf("%d ",c);
return OK;
}

/* 構造一個空棧S */
Status InitStack(SqDoubleStack *S)
{
S->top1=-1;
S->top2=MAXSIZE;
return OK;
}

/* 把S置為空白棧 */
Status ClearStack(SqDoubleStack *S)
{
S->top1=-1;
S->top2=MAXSIZE;
return OK;
}

/* 若棧S為空白棧,則返回TRUE,否則返回FALSE */
Status StackEmpty(SqDoubleStack S)
{
if (S.top1==-1 && S.top2==MAXSIZE)
return TRUE;
else
return FALSE;
}

/* 返回S的元素個數,即棧的長度 */
int StackLength(SqDoubleStack S)
{
return (S.top1+1)+(MAXSIZE-S.top2);
}

/* 插入元素e為新的棧頂元素 */
Status Push(SqDoubleStack *S,SElemType e,int stackNumber)
{
if (S->top1+1==S->top2)/* 棧已滿,不能再push新元素了 */
return ERROR;
if (stackNumber==1)/* 棧1有元素進棧 */
S->data[++S->top1]=e; /* 若是棧1則先top1+1後給數組元素賦值。 */
else if (stackNumber==2)/* 棧2有元素進棧 */
S->data[--S->top2]=e; /* 若是棧2則先top2-1後給數組元素賦值。 */
return OK;
}

/* 若棧不空,則刪除S的棧頂元素,用e返回其值,並返回OK;否則返回ERROR */
Status Pop(SqDoubleStack *S,SElemType *e,int stackNumber)
{
if (stackNumber==1)
{
if (S->top1==-1)
return ERROR; /* 說明棧1已經是空棧,溢出 */
*e=S->data[S->top1--]; /* 將棧1的棧頂元素出棧 */
}
else if (stackNumber==2)
{
if (S->top2==MAXSIZE)
return ERROR; /* 說明棧2已經是空棧,溢出 */
*e=S->data[S->top2++]; /* 將棧2的棧頂元素出棧 */
}
return OK;
}

Status StackTraverse(SqDoubleStack S)
{
int i;
i=0;
while(i<=S.top1)
{
visit(S.data[i++]);
}
i=S.top2;
while(i<MAXSIZE)
{
visit(S.data[i++]);
}
printf("\n");
return OK;
}

int main()
{
int j;
SqDoubleStack s;
int e;
if(InitStack(&s)==OK)
{
for(j=1;j<=5;j++)
Push(&s,j,1);
for(j=MAXSIZE;j>=MAXSIZE-2;j--)
Push(&s,j,2);
}

printf("棧中元素依次為:");
StackTraverse(s);

printf("當前棧中元素有:%d \n",StackLength(s));

Pop(&s,&e,2);
printf("彈出的棧頂元素 e=%d\n",e);
printf("棧空否:%d(1:空 0:否)\n",StackEmpty(s));

for(j=6;j<=MAXSIZE-2;j++)
Push(&s,j,1);

printf("棧中元素依次為:");
StackTraverse(s);

printf("棧滿否:%d(1:否 0:滿)\n",Push(&s,100,1));


ClearStack(&s);
printf("清空棧後,棧空否:%d(1:空 0:否)\n",StackEmpty(s));

return 0;
}

兩棧共用空間的C語言實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.