程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> 兩棧共享空間的c語言實現

兩棧共享空間的c語言實現

編輯:關於C

1. 兩棧共享空間結構

typedef struct 
{
        SElemType data[MAXSIZE];
        int top1;	/* 棧1棧頂指針 */
        int top2;	/* 棧2棧頂指針 */
}SqDoubleStack;


2. 構造一個空棧S

Status InitStack(SqDoubleStack *S)
{ 
        S->top1=-1;
        S->top2=MAXSIZE;
        return OK;
}


3. 把S置為空棧

Status ClearStack(SqDoubleStack *S)
{ 
        S->top1=-1;
        S->top2=MAXSIZE;
        return OK;
}


4.若棧S為空棧,則返回TRUE,否則返回FALSE

Status StackEmpty(SqDoubleStack S)
{ 
        if (S.top1==-1 && S.top2==MAXSIZE)
                return TRUE;
        else
                return FALSE;
}


5.返回S的元素個數,即棧的長度

int StackLength(SqDoubleStack S)
{ 
        return (S.top1+1)+(MAXSIZE-S.top2);
}


6.插入元素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;
}


7.若棧不空,則刪除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;
}


8.顯示全部元素

Status StackTraverse(SqDoubleStack S)
{
        int i;
        i=0;
        while(i<=S.top1)
        {
                visit(S.data[i++]);
        }
        i=S.top2;
        while(i


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


參考<<大話數據結構>>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved