資料結構–關於線性表插入元素

來源:互聯網
上載者:User
#include <iostream>using namespace std;#define LIST_INIT_SIZE 100 //初始化分配量#define LISTINCREMENT 10 //儲存空間的分配增量typedef int Status;typedef int ElemType;typedef struct{ElemType *elem;//儲存空間基址int length;//當前長度int listsize;//當前的分配的儲存容量 (以sizeof (ElemType)為單位)}SqList;Status InitList_sq(SqList &L){L.elem = (ElemType *)malloc(LIST_INIT_SIZE *sizeof(ElemType));if ( !L.elem)exit(1);//儲存分配失敗L.length = 0; //空表長度為0L.listsize =LIST_INIT_SIZE;//初始儲存容量return true;}Status ListInsert_Sq(SqList &L,int i,ElemType e)    {        //在順序線性表L中第i個位置之前插入新的元素e          //i的合法值為1<=i<=ListLength_Sq(L)+1          if(i <1 || i> L.length + 1)            return false;   //i值不合法          if(L.length >= L.listsize)   //當前儲存空間已滿,增加分配          {            ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize + LISTINCREMENT )* sizeof(ElemType));            if(!newbase)                exit(1);    //儲存分配失敗              L.elem = newbase;//新基址              L.listsize += LISTINCREMENT;    //增加儲存容量          }            ElemType *q = &(L.elem[i-1]);//q為插入位置              for(ElemType *p = &(L.elem[L.length-1]);p>=q;--p)            *(p+1) = *p;    //插入位置及之後的元素右移              *q = e;     //插入e          ++L.length;     //表長增1   ElemType l = *q; //用一個自訂的變數 返回指標q中所指代的值    return l;    }   int main()    {        SqList L;          InitList_sq(L);                 ElemType s = ListInsert_Sq(L,1,1234);           cout << s <<endl;          return 0;    }   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.