1.先做头文件List.h ,注意预编译处理
#ifndef LIST__H__
#define LIST__H__
#include <iostream>
#include <stdexcept>
using namespace std;
typedef int T;
class List
{
private:
struct Node
{
T data;
Node* next;
Node(const T& d):data(d),next()
{
}
};
Node* head;
int sz;
Node*& getptr(int pos);
public:
List():head(),sz()
{
}
~List()
{
clear();
}
List& insert(const T& d,int pos = 0);
void travel();
void clear();
bool erase(int pos);
void remove(const T& d);
bool set(const T& d,int pos);
int find(const T& d);
int size()
{
return sz;
}
T& at(int pos);
void push_front(const T& d)
{
insert(d,0);
}
void push_back(const T& d)
{
insert(d,sz);
}
void pop_front()
{
erase(0);
}
void pop_back()
{
erase(sz-1);
}
};
#endif
2.再做cpp文件 ,注意这里没有main函数,除了函数的定义外,只包含了List.h文件
#include "List.h"
List::Node*& List::getptr(int pos)
{
if(pos < 0 || pos > sz)
{
pos = 0;
}
if(pos == 0)
{
return head;
}
Node* p = head;
for(int i = 0; i < pos -1 ; i++)
{
p = p->next;
}
return p->next;
}
List& List::insert(const T& d,int pos)
{
Node* pn = new Node(d);
Node*& ptr = getptr(pos);
pn->next = ptr;
ptr = pn;
sz++;
return *this;
}
void List::travel()
{
Node* p = head;
while(p)
{
cout << p->data << ' ' ;
p = p->next;
}
cout << endl;
}
void List::clear()
{
Node* p = head;
while(head)
{
head = head->next;
delete p;
p = head;
}
sz = 0;
}
bool List::erase(int pos)
{
if(pos < 0 || pos >= sz)
{
return false;
}
Node*& ptr = getptr(pos);
Node* p = ptr;
ptr = ptr->next;
delete p;
sz--;
return true;
}
int List::find(const T& d)
{
int pos = 0;
Node* p = head;
while(p)
{
if(p->data == d)
{
return pos;
}
//曾经把下面两行写入了if
p = p->next;
pos++;
}
return -1;
}
void List::remove(const T& d)
{
int pos;
while((pos = find(d)) != -1)
{
erase(pos);
}
}
bool List::set(const T& d,int pos)
{
if(pos < 0 || pos >= sz)
{
return false;
}
Node*& ptr = getptr(pos);
ptr->data = d;
return true;
}
T& List::at(int pos)
{
if(pos < 0 || pos >= sz)
{
throw out_of_range("out");
}
//曾把下两句写到了if
Node*& ptr = getptr(pos);
return ptr->data;
}
3.最后做一个测试的cpp ,这里要注意头文件的包含
想要程序运行,首先编译List.cpp ==> g++ -c List.cpp
然后编译test.cpp ==> g++ -c test.cpp
接着连接 ==> g++ List.o test.o
最后执行 ==> ./a.out
哦了。
#include <iostream>
#include "List.h"
int main()
{
List list;
list.insert(10);
list.travel();
cout << "好了,已经将List做成头文件和cpp文件了,以后可以将其当作工具类了。测试结束。" << endl;
}