手寫vector

因爲不會構造函數,所以請在使用時先init一下。

#include<bits/stdc++.h>
using namespace std;
class array{
    public:
        void push_back(int x){
                if(begin==NULL)clear();
            last->count=x;
            k=last;
            last=new unit;
            last->next=NULL;
            last->front=k;
            k->next=last;
            len++;
        }
        void clear(){
            for(i=begin;i!=last;i=k){
                k=i->next;
                delete i;
            }
            delete last;
            len=0;
            init();
        }
        int at(int x){
            i=begin;
            for(j=0;j<=x;j++)
                i=i->next;
            return i->count;
        }
        void pop_back(){
            k=last->front;
            delete last;
            k->next=NULL;
            last=k;
            len--;
        }
        int size(){
            return len;
        }
        bool empty(){
            return len==0;
        }
        void swap(array x,array y){
                if(x.begin==NULL)clear();
                if(y.begin==NULL)clear();
            array *x1=&x,*x2=&y,*x3;
            x3=x1;
            x1=x2;
            x2=x3;
        }
    private:
        struct unit{
            int count;
            struct unit *next,*front;
        };
        void init(){
            begin=new unit;
            last=new unit;
            begin->next=last;
            last->front=begin;
            begin->count=0;
            begin->front=NULL;
            last->next=NULL;
            last->count=0;
        }
        unit *begin,*cur,*last,*k,*i;
        int len,j;
};

效率分析:

操作 時間效率
插入 O(1) 
初始化 O(1) 
清空 O(n) 
詢問 O(n) 
彈出 O(1) 
求長 O(1) 
判空 O(1) 
交換 O(1) 
發佈了54 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章