顺序表

顺序表

//
//  顺序表
//  TestList
//
//  Created by chenshang on 14-2-7.
//  Copyright (c) 2014年 chenshang. All rights reserved.
//

#ifndef TestList_SeqList_h
#define TestList_SeqList_h


#include <iostream>
using namespace std;
typedef  int  T;
const int DefaultSize=100;

class SeqList{
public:
    SeqList(int sz=DefaultSize):maxSize(sz),currentSize(-1){
        if (sz>0) {
            arr = new T[maxSize];
        }
    }
    ~SeqList(){
        delete[] arr;
    }
public:
    int length() const{
        return currentSize+1;
    }
    int find(T x)const; // 找到值为x的位置
    bool isElement(T x) const;  //is it in the list
    bool insert(T x,int i);
    bool remove(T x);

    bool isEmpty(){
        return currentSize==-1;
    }
    bool isFull(){
        return currentSize == maxSize-1;
    }

    int Get(int i){
        return i<0||i>currentSize ? (cout<<"can not find the element"<<endl,0):arr[i];
    }
    
    void print();
    
private:
    int *arr;
    int maxSize;
    int currentSize;
};

int SeqList::find(T x)const{
    for (int i=0; i<currentSize; i++) {
        if (arr[i]==x) {
            return i;
        }
    }
    cout<<"can not find the element you want to find"<<endl;
    return -1;
}

bool SeqList::isElement(T x)const{
    if (find(x)==-1) {
        return false;
    }
    return true;
}
bool SeqList::insert(T x,int i){
    if (i<0||i>currentSize+1||currentSize==maxSize-1) {
        cout<<"the operate is illegal"<<endl;
        return false;
    }
    currentSize++;
    for (int j=currentSize; j>i; j--) {
        arr[currentSize]=arr[j-1];
    }
    arr[i]=x;
    return true;
}
bool SeqList::remove(T x){
    int size = currentSize;
    for (int i=0; i<currentSize; i++) {
        if (arr[i]==x) {
            for (int j=i; j<currentSize; j++) {
                arr[j]=arr[j+1];
            }
            currentSize--;
            continue;
        }
    }
    if (size==currentSize) {
        cout<<"can not find the element you want to remove"<<endl;
        return false;
    }
    return true;
}
void SeqList::print(){
    for (int i=0; i<currentSize; i++) {
        cout<<i+1<<":\t"<<arr[i]<<endl;
    }
    cout<<endl<<endl;
}


#endif


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值