线性表(数组、链式)

数组实现:

#include "stdafx.h"
#include<iostream>
using namespace std;

#define MAXSIZE 5
class Mylist
{
public:
    Mylist() :last(-1) { data = new int[MAXSIZE]; }
    int Find(int x);
    void insert(int x, int i);
    void Delete(int i);
    void print() { for (int i = 0; i < MAXSIZE; i++) cout << data[i] << endl; }
    ~Mylist() {  }
private:
    int * data;
    int last;
};
int Mylist::Find(int x)
{
    int i = 0;
    while (i <= last && data[i] != x)
        i++;
    if (i > last) return -1;
    else return i+1;
}
void Mylist::insert(int x, int i)
{
    int j;
    if (last == MAXSIZE - 1)
    {
        cout << "full"<<endl;
        return;
    }
    if (i<1 || i>last + 2)
    {
        cout << "illegal"<<endl;
        return;
    }
    for (j = last; j >= i - 1; j--)
        data[j + 1] = data[j];
    data[i - 1] = x;
    last++;
    return;
}
void Mylist::Delete(int i)
{
    int j;
    if (i<1 || i>last + 1)
    {
        cout << "not in" << endl;
        return;
    }
    for (j = i; j <= last; j++)
        data[j - 1] = data[j];
    last--;
    return;
}
int main()
{
    Mylist newlist;
    newlist.print();
    newlist.insert(3, 1);
    newlist.insert(5, 2);
    newlist.insert(6, 3);
    newlist.insert(8, 4);
    newlist.insert(9, 5);
    cout<<newlist.Find(3)<<endl;
    newlist.Delete(2);
    newlist.print();
    return 0;
}

 

posted @ 2018-01-05 10:58  燕子不呢喃  阅读(231)  评论(0编辑  收藏  举报