1: //sqlist.cpp
2: #include "sqlist.h"
3: #include <iostream>
4:
5: void SqList::InitList()
6: {
7: length = 0;
8: }
9:
10: bool SqList::ListEmpty()
11: {
12: return (0 == length);
13: }
14:
15: void SqList::ClearList()
16: {
17: length = 0;
18: }
19:
20: void SqList::GetElem(int i, ElemType *e)
21: {
22: *e = data[i];
23: }
24: int SqList::LocateElem(ElemType e)
25: {
26: int i = 0;
27: while(i++ < length)
28: {
29: if(data[i] == e)
30: {
31: cout<<"Find it."<<endl;
32: return i;
33: }
34: }
35: cout<<"Cannot find it."<<endl;
36: return -1;
37: }
38:
39: void SqList::ListInsert(int i, ElemType e)
40: {
41: int len = length;
42: while(len > i)
43: {
44: data[len] = data[len - 1];
45: --len;
46: }
47: data[i] = e;
48: length += 1;
49: }
50:
51: void SqList::ListDelete(int i, ElemType *e)
52: {
53: int loc = i;
54: length -= 1;
55:
56: while(loc < length)
57: {
58: data[loc] = data[loc+1];
59: ++loc;
60: }
61: }
62:
63: void SqList::ShowList()
64: {
65: int len = 0;
66: cout<<"Show the List:"<<endl;
67: while( len++ < length )
68: {
69: cout<<"location len: %d."<<data[len]<<endl;
70: }
71: }
72:
73: int SqList::ListLength()
74: {
75: return length;
76: }
1: //sqlist.h
2: #ifndef SQLIST_H_H
3: #define SQLIST_H_H
4:
5: #define MAXSIZE 20
6: typedef int ElemType;
7: using namespace std;
8:
9: class SqList
10: {
11: public:
12: void InitList();//初始化,建立空线性表L
13: bool ListEmpty();//表空返回TRUE,否则FALSE
14: void ClearList();//清空线性表
15: void GetElem(int i, ElemType *e ); //把i位置元素返回给e
16: int LocateElem(ElemType e ); //查找e,返回e的位置
17: void ListInsert(int i,ElemType e ); //位置i插入e
18: void ListDelete(int i,ElemType *e ); //删除i位置元素,值用e返回
19: int ListLength(); //返回元素个数
20: void ShowList();//遍历
21:
22: private:
23: ElemType data[MAXSIZE];
24: int length;
25: }
26: #endif
1: #include "sqlist.h"
2: #include <iostream>
3:
4: int main(int argc, char * argv[])
5: {
6: int data;
7: int loc;
8: int len;
9: bool bEmpty;
10:
11: SqList sqlist;
12: sqlist.InitList();
13: cout<<"InitList complete!"<<endl;
14:
15: bEmpty = sqlist.ListEmpty();
16: if(bEmpty)
17: cout<<"sqlist is empty."<<endl;
18:
19: sqlist.ShowList();
20:
21: sqlist.ListInsert(0, 1 );
22: sqlist.ListInsert(1, 2 );
23: sqlist.ListInsert(2, 3 );
24:
25: sqlist.ShowList();
26:
27: sqlist.GetElem(1, &data );
28: cout<<"2nd data is %d."<<data<<endl;
29:
30: loc = sqlist.LocateElem(2 );
31: cout<<"data 2 is in location %d."<<loc<<endl;
32:
33:
34:
35: sqlist.ListDelete(&sqlist, 0, &data );
36: printf("delete data in location 0.
");
37:
38: sqlist.ShowList();
39:
40: len = sqlist.ListLength();
41: cout<<"length is %d."<<len<<endl;
42:
43: sqlist.ClearList();
44: sqlist.ShowList();
45:
46: return 0;
47: }