DS之順序表實現輸入資料逆置,ds順序資料

來源:互聯網
上載者:User

DS之順序表實現輸入資料逆置,ds順序資料

        實現輸入資料逆置和順序表實現排序是兩個極其相似的過程,因此使用的順序表的基本操作也是一樣的:0基本操作前的準備,1初始化順序表,6向順序表插入資料元素。

        要想實現輸入資料元素的逆置還需要一個逆置函數,逆置函數在C++,C#語言中早已接觸過,因此不陌生,記得在做大量的C++的程式碼補充的大題就寫過不下數十遍,挺簡單的掌握技巧,就是你輸入資料的個數的一半,前後進行交換,因此逆置函數的代碼為:

<span style="font-size:18px;">//逆置函數void nizhi(SqList &L){    for(int i=0;i<L.length/2;i++)    {   int temp;   temp=L.elem[i];   L.elem[i]=L.elem[L.length-1-i];       L.elem[L.length-1-i]=temp;    } }</span>

         而在主函數中只需要聲明一個順序表,輸入順序表資料元素的個數和資料,調用逆置函數,即可實現。完整的順序表實現輸入資料逆置的代碼為:

<span style="font-size:18px;">#include <iostream> using namespace std; #include <malloc.h>#include <stdlib.h>#define LIST_INIT_SIZE 100  #define LISTINCREMENT  10#define OK 1#define TRUE 1#define FALSE 0#define ERROR 0#define OVERFLOW -2typedef int ElemType;typedef int Status;typedef struct{ElemType *elem;int length;int listsize;}SqList;//定義了一個結構體類型,並命名為Sqlist//1初始化順序表Status InitList(SqList &L){    L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));if(!L.elem)    {       exit(OVERFLOW);}L.length=0;//長度為0L.listsize=LIST_INIT_SIZE; return OK;}//6向順序表插入資料元素Status ListInsert(SqList &L,int i, ElemType e){if(i<1||i>L.length+1){return ERROR;}if (L.length>=L.listsize){        ElemType * newbase=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT )*sizeof(ElemType));        if(!newbase) {exit(OVERFLOW);}        L.elem=newbase;        L.listsize+=LISTINCREMENT;}    ElemType *q=&(L.elem[i-1]);    ElemType *p;for(p=&(L.elem[L.length-1]);p>=q;--p){*(p+1)=*p;}*q=e;++L.length;return OK;}//逆置函數void nizhi(SqList &L){    for(int i=0;i<L.length/2;i++)    {   int temp;   temp=L.elem[i];   L.elem[i]=L.elem[L.length-1-i];       L.elem[L.length-1-i]=temp;    } }int main(){   SqList La;    InitList(La);ElemType e;    int na;    cout<<"請輸入La中資料的個數:";cin>>na;for(int i=1;i<=na;i++) {      cin>>e;      ListInsert(La,i,e);}nizhi(La);//調用逆置函數    for(i=0;i<La.length;i++){cout<<La.elem[i]<<",";}    cout<<endl;    return 0;}</span>

         輸入資料為:順序表的個數為10

         輸入的資料元素為:0 1 2 3 4 5 6 7 8 9

         輸出的結果為:

 


 


 

 

相關文章

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.