线性表—使用数组实现

线性表的功能有:

1)求表的长度

2)按位查找

3)在第i个位置中插入值为n的数

4)删除线性表的第i 个元素

5 )输出线性表

 1 //在头文件中"SeqList.h"
 2 const int MaxSize=100;
 3 #define T float //此处修改 数组的类型
 4 class SeqList
 5 {
 6 public:
 7     SeqList(){length=0;}
 8     SeqList(T a[],int n);
 9     ~SeqList() {}
10     int Length(){return length;}
11     T Get(int i);
12     T Locate(int x);
13     void Insert(int i,int x);
14     T Delete(int i);
15     void PrintList();
16 private:
17     T data[MaxSize];
18     int length;
19 };
 1 //在SwqList.cpp
 2 #ifndef SEQLIST_H_
 3 
 4 #define SEQLIST_H_
 5 #include "SeqList.h"
 6 #include<iostream>
 7 using namespace std;
 8 SeqList::SeqList(T *a,int n)
 9 {
10     if(n>MaxSize) throw"Parameters of illegal";
11     for(int i=0;i<n;i++)
12         data[i]=a[i];
13     length=n;
14 }
15 
16 void SeqList::Insert(int i,int x)
17 {
18     if(length>=MaxSize) throw"overflow";
19     if(i<1||i>length+1) throw"malposition";
20     for(int j=length;j>=i;j--)
21         data[j]=data[j-1];
22     data[i-1]=x;
23     length++;
24 }
25 
26 
27 T SeqList::Delete(int i)
28 {
29     if(length==0) throw "underflow";
30    // if(i<1||i>length) "malposition";
31     int x=data[i-1];
32     for(int j=i;j<length;j++)
33         data[j-1]=data[j];
34     length--;
35     return x;
36 }
37 
38 T SeqList::Get(int i)
39 {
40     if(i<1||i>length) throw "malposition";
41     else return data[i-1];
42 }
43 
44 T SeqList::Locate(int x)
45 {
46     for(int i=0;i<length;i++)
47         if(data[i]==x) return i+1;
48     return 0;
49 }
50 
51 void SeqList::PrintList()
52     {
53         for(int i=1;i<=length;i++)
54         i%10==0?cout<<data[i-1]<<"\n":cout<<data[i-1]<<"\t";
55     };
56 #endif // SwqList_H_

 

 

posted @ 2013-10-25 16:50  退之  阅读(375)  评论(0编辑  收藏  举报