C++ 数据结构线性表-数组实现
线性表的数组实现,实现几个核心的功能,语言是C++,如果有更好的想法和意见,欢迎留言~~~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
/* Author : Moyiii
* 线性表的数组实现,仅作学习之用,当然如果
* 你想拿去用,随你好啦。
*/
#include<iostream>
using namespace std;
//顺序表
class SeqList
{
public :
//构造函数,接受一个默认的列表大小
SeqList( int size = MAX_LIST_SIZE);
//析构函数,释放elems占用的内存空间
~SeqList();
//清空表
void clear();
//判断表是否为空
bool isEmpty();
//获得表的当前元素个数
int getLength();
//在第pos个元素位置之前插入一个新元素
bool insertElem( int pos, int elem);
//删除第pos个元素
bool deleteElem( int pos);
//打印表中元素
void print();
int *elems; //表元素,
private :
static const int MAX_LIST_SIZE;
int m_length; //表的元素个数
int m_size; //表的当前最大长度
};
SeqList :: SeqList( int size)
{
//size不可以小于零,也不可以超过系统规定最大长度
//否则做截断处理
if (size > MAX_LIST_SIZE)
{
m_size = MAX_LIST_SIZE;
}
else if (size < 0)
{
m_size = 0;
}
else
{
m_size = size;
}
elems = new int [m_size];
m_length = 0;
if (!elems)
{
cout << "Space allocate failed!" << endl;
}
}
SeqList :: ~SeqList()
{
delete []elems;
}
void SeqList :: clear()
{
m_length = 0;
}
bool SeqList :: isEmpty()
{
if (m_length == 0)
{
return true ;
}
else
{
return false ;
}
}
int SeqList :: getLength()
{
return m_length;
}
bool SeqList :: insertElem( int pos, int elem)
{
if (m_length == m_size)
{
cout << "List is Full" << endl;
return false ;
}
if (pos < 1 || pos > m_length + 1)
{
cout << "Over Bound!" << endl;
return false ;
}
//插入位置之后元素后移
for ( int i = m_length; i >= pos - 1; --i)
{
elems[i+1] = elems[i];
}
elems[pos-1] = elem;
m_length++;
return true ;
}
bool SeqList :: deleteElem( int pos)
{
if (pos < 1 || pos > m_length)
{
return false ;
}
for ( int i = pos - 1; i <= m_length - 1; ++i)
{
elems[i] = elems[i+1];
}
m_length--;
return false ;
}
void SeqList :: print()
{
for ( int i = 0; i < m_length; ++i)
{
cout << elems[i] << " " ;
}
cout << endl;
}
//初始化
const int SeqList :: MAX_LIST_SIZE = 100;
int main()
{
SeqList myList;
for ( int i = 1; i <= 10; ++i)
{
myList.insertElem(1,i);
}
myList.print();
cout << "Length= " << myList.getLength() <<endl;
myList.deleteElem(5);
myList.print();
cout << "Length= " << myList.getLength() <<endl;
myList.clear();
cout << myList.isEmpty() << endl;
return 0;
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/Moyiii/article/details/40821525