轉載請註明出處:http://blog.csdn.net/ns_code/article/details/22312565
題目:
Describe how you could use a single array to implement three stacks.
翻譯:
只用一個數組實現三個棧
思路:
用一個數組實現一個棧很容易,我們在Q3.1中也是用數組來類比棧的。如果要用一個數組來實現三個棧,在壓棧的時候,不管是哪個棧的push操作,直接將元素順序壓入到數組中,同時將本棧的棧頂索引指標指剛剛壓入的元素即可,如所示(三種顏色分別代表三個棧,箭頭指向每個棧的棧頂):
但在pop的時候,我們需要將棧頂指標向下移動,將其指向本棧中的下一個元素,這就需要在每個元素中加上一個指向本棧中下一個元素的索引。已讓如所示,如果令最底部元素在數組中的位置需要為0,那麼棧頂元素12所指的下一個元素的位置序號為9,即元素10,棧頂元素11所指向的下一個元素的位置序號為6,即元素7,而棧頂元素9所指向的下一個元素的位置序號為7,即元素8。這樣,我們就需要將數組中的節點儲存為如下結構:
typedef struct node{ElemType data;int next;//指向該棧的下一個元素,如果沒有下一個元素,則設next為-1}node; 實現代碼:
/****************************************************題目描述:用一個數組實現三個棧Date:2014-03-27*****************************************************/typedef int ElemType;#define MAX 100 //三個棧的總深度#include<stdio.h>typedef struct node{ElemType data;int next;//指向該棧的下一個元素,如果沒有下一個元素,則設next為-1}node;/*在該棧頂的索引指標為top時,向棧A中壓入資料datacount用來記錄最上面的元素所在棧的棧頂位置*/bool push(node *A,int &count,int &top,ElemType data){if(count>=MAX-1 || count<-1 || top>count || top<-1)return false;count++;A[count].data = data;A[count].next = top;top = count; return true;}/*在該棧頂索引指標為top時,出棧count用來記錄最上面的元素所在棧的棧頂位置*/bool pop(node *A,int &count,int &top){if(top<0 || top>count)return false;if(top == count)count--;A[top].data = -10; //這裡為了便於觀察pop後的情況,將出棧後的位置的元素設定為-10top = A[top].next;return true;}int main(){int top1 = -1;int top2 = -1;int top3 = -1;int count = -1;node A[MAX];push(A,count,top1,1);push(A,count,top2,2);push(A,count,top3,3);push(A,count,top1,4);push(A,count,top3,5);push(A,count,top3,6);push(A,count,top2,7);push(A,count,top1,8);int i;printf("After pushed:\n");for(i=0;i<8;i++)printf("A[%d].data = %d,A[%d].next = %d\n",i,A[i].data,i,A[i].next);pop(A,count,top3);pop(A,count,top2);pop(A,count,top1);printf("After popd:\n");for(i=0;i<8;i++)printf("A[%d].data = %d,A[%d].next = %d\n",i,A[i].data,i,A[i].next);return 0;} 測試結果:
註:代碼開源到我的Github:https://github.com/mmc-maodun/CareerCup