main.cpp
1 #include "myDataBase.h"
2
3 int main()
4 {
5 int i =0;
6 myDataBase::GetInstance().createDataBaseList();
7 for(i=0;i<3 ; ++i)
8 {
9 string str;
10 cin >> str;
11 myDataBase::GetInstance().InsertListDataTail(i,str);
12 }
13 myDataBase::GetInstance().ShowDataBaseList();
14
15 return 0;
16 }
myDataBase.h
1 #ifndef _MYDATABASE_H
2 #define _MYDATABASE_H
3
4 #include <cstddef>//NULL 需要使用的头文件
5 #include <iostream>
6 #include <strings.h>
7 using namespace std;
8
9 //Data content
10 class dataContent{
11 public:
12 int key;
13 string name;
14 };
15
16 /*存储连表的class*/
17 class node{
18 public:
19 //数据
20 dataContent data ;
21 //int data;
22 //指向下一个数据区的指针
23 struct node *Next;
24 };
25
26 /*Data content
27 class dataContent{
28 int key;
29 string name;
30 };*/
31
32
33 /*对连表操作的class*/
34 class myDataBase{
35 public:
36 //构造函数
37 myDataBase();
38 //析构函数
39 ~myDataBase();
40 //创建链表
41 void createDataBaseList();
42 //show连表里面的数据
43 void ShowDataBaseList();
44 //数据的尾部插入操作
45 bool InsertListDataTail(int data,std::string & name);
46 //获取类的句柄
47 static myDataBase& GetInstance();
48
49 private:
50 //定义了头节点
51 node *pNode;
52 };
53
54 #endif
myDataBase.cpp
1 #include "myDataBase.h"
2
3 myDataBase::myDataBase()
4 {
5 pNode = NULL;
6 }
7
8 void myDataBase::createDataBaseList()
9 {
10 pNode = new node;
11
12 pNode->data.key=0;
13 pNode->Next = NULL;
14
15 return ;
16 }
17
18
19 bool myDataBase::InsertListDataTail(int data, std::string & name)
20 {
21 node * subNode = new node;
22 if(subNode == NULL)
23 {
24 cout<< "subNode create error!"<<endl;
25
26 return false;
27 }
28
29 subNode->data.key = data;
30 subNode->data.name = name;
31 subNode->Next = NULL;
32
33 node *temNode = pNode;
34
35 while(temNode->Next != NULL)
36 {
37 temNode = temNode->Next;
38 }
39
40 temNode->Next = subNode;
41
42 return true;
43 }
44
45
46 void myDataBase::ShowDataBaseList()
47 {
48 node * tempNode = pNode;
49 if(tempNode == NULL)
50 {
51 return ;
52 }
53
54 do{
55 if( (tempNode = tempNode->Next ) == NULL )
56 {
57 break;
58 }
59 else
60 {
61 cout<<"key: "<<tempNode->data.key<<" name :"<<tempNode->data.name<<endl;
62 }
63 }while(tempNode->Next);
64
65 return ;
66 }
67
68
69 static myDataBase *m_instance = NULL;
70
71 myDataBase &myDataBase::GetInstance()
72 {
73 if(m_instance == NULL)
74 {
75 m_instance = new myDataBase;
76 if(m_instance == NULL)
77 {
78 cout<< "create myDataBase class err!"<<endl;
79 exit(0);
80 }
81 }
82 return *m_instance;
83 }
1 运行结果显示
2 ****@****:~/桌面/myDataBaseList/myDataBaseList$ ./main
3 i
4 love
5 u
6 key: 0 name :i
7 key: 1 name :love
8 key: 2 name :u
9 zhou_jiang@zhoujiang: