C/C++學習(六)線性表的插入、刪除和查找

 

查找

查找線性表是最基本的操作之一,比如根據序號查找元素的值,或者根據值查找該值是否在線性表中,如果在,那麼序號是幾等等。

 

插入

  1. 如果插入的位置不合理,那麼就拋出異常。
  2. 如果線性表長度大於等於數組長度,則拋出異常或者動態增加容量。
  3. 從最後一個元素開始向前遍歷到第i個位置,分別將它們都向後移動一個位置。
  4. 將要插入的元素填入位置i處。
  5. 表長加1。

刪除

  1. 如果刪除位置不合理,拋出異常
  2. 取出刪除元素
  3. 從刪除元素位置開始遍歷到最後一個元素位置,分別將它們向前移動一個位置
  4. 表長減1.

 

#include <iostream>


using namespace std;
const int LIST_INIT_SIZE=100;
const int LISTINCERMENT=10;

template<typename T>
class Sqlist
{
private:
    T *elem;
    T *newbase;
    int *p;
    int *q;
    int length;//
    int listsize;
public:
    Sqlist(int a[] , int n)
    {
        elem = new T[LIST_INIT_SIZE];//分配內存
        memcpy(elem, a, LIST_INIT_SIZE*sizeof(T));
        p = NULL;
        q = NULL;
//        elem = NULL;
        if(!elem)
            cout << "OVRELOW1" <<endl;
        length=n;
        listsize = LIST_INIT_SIZE;
    }
    T* ListInsert(int i, T e)
    {
        if((i<1) || (i>length+1))
        {
            cout << "ERROR1" <<endl;
            return 0;
        }
        if(length >= listsize)//當存儲空間已滿,增加分配
         {

            newbase = new T[listsize+LISTINCERMENT];
        if(!newbase)
            cout << "OVERFLOW2" << endl;
           elem = newbase;
           listsize += LISTINCERMENT;//增加存儲容量
        }


        q = &elem[i-1];//q爲插入位置
        for(p=&(elem[length-1]);p>=q;--p)//插入位置及之後的元素右移

           *(p+1) = *p;
           *q = e; //插入e
           ++length;

        return elem;

    }
    T* ListDelete(int i)
    {
        if((i<1) || (i>length))
        {
            cout << "ERROR1" <<endl;
            return 0;
        }
        p=&elem[i-1];//p爲被刪除的位置
//        e=*p;
        q=elem+length-1;//表尾元素的位置
        for(;p<=q;++p)//被刪除元素之後的元素左移
            *(p-1) = *p;
        --length;
        return elem;
    }
    int LocateElem_Sq(T e)//
    {
        int i=1;//i的初值爲第一個元素的位序
        p=elem;//p的初值爲第一個元素的存儲位置
        while(i <= length && !(*p==e))
            ++i;
        if(i <= length)
            return i;
    }
    void getelem()//依次得出elem的值
    {
        for(int i=0; i<length; i++)
            cout << elem[i] << "  ";
    }

    ~Sqlist()
    {
        delete elem;//釋放分配內存
        delete newbase;
        delete p;
        delete q;
    }
};
int main()
{
//    cout << "Hello World!" << endl;
    int(n);
    int a[5] = {4,8,7,5,10};
    Sqlist<int> list(a,5);
    list.ListInsert(1,6);
    list.ListInsert(3,45);
    list.ListInsert(5,100);
    list.getelem();
    cout << endl;
    list.ListDelete(1);
    list.ListDelete(2);
    list.getelem();
    cout << endl;
    cout <<  list.LocateElem_Sq(10) << endl;
//    cout << n << endl;
    return 0;
}

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章