1. 程式人生 > 其它 >棧和佇列的基本操作-線上性表L中第i個數據元素之前插入資料元素x-順序棧的其他基本演算法

棧和佇列的基本操作-線上性表L中第i個數據元素之前插入資料元素x-順序棧的其他基本演算法

一、實驗目的

1.熟練掌握棧和佇列的特點。

2.掌握棧和佇列的定義和基本操作,熟練掌握順序棧和鏈式佇列的操作及應用。

二、實驗內容

(一)順序棧

  1. 首先將順序棧儲存結構定義放在一個頭檔案:如取名為SqStackDef.h。
  2. 將順序棧的基本操作演算法也集中放在一個檔案之中,如取名為SqStackAlgo.h。
  3. 將函式的測試和主函式組合成一個檔案,如取名為SqStackUse.cpp。

(二)鏈式佇列

  1. 首先將鏈式佇列的儲存結構定義放在一個頭檔案:如取名為LinkQueueDef.h。
  2. 將鏈式佇列的基本操作演算法也集中放在一個檔案之中,如取名為LinkQueueAlgo.h。
  3. 將函式的測試和主函式組合成一個檔案,如取名為LinkQueueUse.cpp。

三、實驗步驟

順序棧

  1. 檔案SqStackDef.h中實現了棧的順序儲存表示
#include<iostream.h>

#define MAXSIZE 100 

#define ok 1

#define error 0

#define overflow -2

typedef int elemtype;

typedef int status;

typedef struct

{elemtype *elem;

int length;

}sqlist;

status init_sq(sqlist &L)                                                     

{

    L.elem
=new elemtype[MAXSIZE]; if(L.elem==NULL)return error; else {L.length=0; return ok;} }

2.檔案SqStackAlgo.h 中實現順序棧的基本操作(儲存結構由SqStackDef.h 定義)

//線上性表L中第i個數據元素之前插入資料元素x

status ListInsert_Sq(sqlist &L,int i,elemtype x) 

{   int j;

   // if(i<1||i>L.length+1)return error;  

     if
(L.length==MAXSIZE)return overflow; // for(j=L.length-1;j>=i-1; j--)//for(j=L.length;j>=i;j--) for(j=L.top-1;j>=i-1; j--) // L.elem[j+1]=L.elem[j]; // L.elem[j]=L.elem[j-1]; L.base[j+1]=L.base[j]; L.elem[i-1]=x; //L.top=x; L.elem[L.length]=x; ++L.length; return ok; } status istDelete_Sq(sqlist &L,int i,elemtype &x) { int j; // if(i<1||i>L.length)return error; if(L.length==0)return error; // for(j=i-1;j<=L.length-2;j++) //L.elem[j]=L.elem[j+1]; x=L.elem[--L.length]; return ok; }

3.在SqStackUse.cpp 檔案中,測試演算法的呼叫,其中間接呼叫了順序棧的其他基本演算法。

status insert_sq(sqlist &L,elemtype x)

{int i;

     if(L.length==MAXSIZE)return error;

       for(i=L.length-1;i>=1;i--)

       if(L.elem[i]<=x)L.elem[i+1]=x;

       L.elem[1]=x;

       L.length++;

       return ok;

}

void hb(sqlist a,sqlist b,sqlist &c)

{

     int i,j,k;

     i=j=k=0;

     c.elem=new elemtype[a.length+b.length];

     while(i<a.length&&j<b.length)

    {if(a.elem[i]<b.elem[j])

     {c.elem[k]=a.elem[i];i++;k++;}

     else {c.elem[k]=b.elem[j];j++;k++;}}

     while(i<a.length)

     {c.elem[k]=a.elem[i];i++;k++;}

while(j<b.length)

   {c.elem[k]=b.elem[j];j++;k++;}

c.length=a.length+b.length;

      

}

main()

{//構造實參

sqlist a,b,c;status  y;int j,i;elemtype e;

y=init_sq(a);

for(j=0;j<5;j++)

cin>>a.elem[j];

a.length=5;

y=init_sq(b);

for(j=0;j<3;j++)

cin>>b.elem[j];

b.length=3;

//呼叫

hb(a,b,c);

//輸出

 for(j=0;j<c.length;j++)

cout<<c.elem[j]<<" ";

四、實驗結果