1 #include<iostream>
2 using namespace std;
3 const int MaxSize = 100;
4 class SeqList
5 {
6 public:
7 SeqList();
8 SeqList(int a[], int n);
9 ~SeqList();
10 int Length();
11 int Get(int i); //按位查找
12 int Locate(int x); //按值查找
13 void Insert(int i, int x);
14 int Delete(int i);
15 void PrintList(); //遍历操作
16 private:
17 int data[MaxSize];
18 int length;
19 };
20 SeqList::~SeqList()
21 {
22 }
23 SeqList::SeqList()
24 {
25 length = 0;
26 }
27 int SeqList::Length()
28 {
29 return length;
30 }
31 SeqList::SeqList(int a[], int n)
32 {
33 if (n > MaxSize)
34 cout<<"参数非法";
35 for (int i = 0; i < n; ++i)
36 {
37 data[i] = a[i];
38 }
39 length = n;
40 }
41 void SeqList::PrintList()
42 {
43 for (int i = 0; i < length; ++i)
44 {
45 cout << data[i]<<"\t";
46 }
47 }
48 int SeqList::Locate(int x)
49 {
50 for (int i=0;i<length;++i)
51 {
52 if (data[i] == x)
53 return i + 1;
54 }
55 return 0;
56 }
57 int SeqList::Get(int i)
58 {
59 if (i<1 && i>length)
60 {
61 cout<<"查找位置非法";
62 }
63 else
64 return data[i - 1];
65 }
66 int SeqList::Delete(int i)
67 {
68 if (length == 0)
69 {
70 throw"下溢";
71 }
72 if (i<1||i>length)
73 {
74 cout<<"位置";
75 }
76 int x = data[i - 1];
77 for (int j = i; j < length; j++)
78 {
79 data[j - 1] = data[j];
80 }
81 length--;
82 return x;
83 }
84 void SeqList::Insert(int i, int x)
85 {
86 if (length >= MaxSize)
87 {
88 cout<<"上溢";
89 }
90 if (i<1||i>length+1)
91 {
92 cout<<"位置异常";
93 }
94 for (int j=length;j>=i;j--)
95 {
96 data[j] = data[j-1];
97 }
98 data[i - 1] = x;
99 length++;
100 }
101 int main()
102 {
103 int r[5] = { 1,5,6,8,4 }, i, x;
104 SeqList L(r, 5);
105 cout << "当前线性表的数据为:"<<endl;
106 L.PrintList();
107 cout << endl;
108 cout << "当前线性表表的长度为:" << endl;
109 cout << L.Length() << endl;
110 cout << "请输入要查找元素的位置:" << endl;
111 cin >> i;
112 x = L.Get(i);
113 cout << "第" << i << "位置的元素为" << x << endl;
114 cout << "请输入在第几个位置插入几:" << endl;
115 cin >> i >> x;
116 L.Insert(i, x);
117 cout << "执行插入操作后数据为:" << endl;
118 L.PrintList();
119 cout << endl;
120 cout << "请输入查找的元素值:"<<endl;
121 cin >> x;
122 i = L.Locate(x);
123 if (0 == i) cout << "查找失败" << endl;
124 else cout << "元素" << x << "的位置为:" << i << endl;
125 cout << "请输入要删除第几个元素:"<<endl;
126 cin >> i;
127 x = L.Delete(i);
128 cout << "删除的元素是" << x << ",删除后数据为:"<<endl;
129 L.PrintList();
130 }
有的要别人来设定目标,有的给别人设定目标;
有的需要感情支持生活,有的需要意志支持生活。