把這裏面的函數名改壹改,再調用內部函數創建新的函數實現歸並、拆分應該不難。
template<typename T>
class List
{
private:
struct Node
{
T data;
Node* next;
Node(const T& t=T()):data(t)
{next=NULL;}
};
Node* head;
Node* getPointer(int pos)
{
Node* p=head;
for(int i=0;i<pos;i++)
p=p->next;
return p;
}
public:
List():head(NULL){};
void clear()
{
while(head!=NULL)
{
Node* p = head->next;
delete head;
head = p;
}
}
~List()
{
clear();
}
void insert_front(const T& t)
{
Node* p = new Node(t);
p->next = head;
head = p;
}
void travel()
{
Node* p = head;
while(p!=NULL)
{
cout<<p->data<<' ';
p = p->next;
}
cout<<endl;
}
void insert_back(const T& t)
{
Node* p = new Node(t);
if(head == 0)
head = p;
else
{
getPointer(size()-1) -> next = p;
}
}
int size()
{
int cnt = 0;
Node* p = head;
while(p != NULL)
{
cnt++;
p = p->next;
}
return cnt;
}
T getHead()
{
if(head == NULL)
throw "No Head";
return head->data;
}
T getTail()
{
if(head == NULL)
throw "No Tail";
Node* p = head;
while(p->next != NULL)
{
p = p->next;
}
return p->data;
}
bool empty()
{
return head==NULL;
}
int find(const T& t)
{
int pos = 0;
Node* p = head;
while(p!=NULL)
{
if(p->data == t)
return pos;
pos++;
p = p->next;
}
return -1;
}
bool updata(const T& o, const T& n)
{
int pos = find(o);
if(pos == -1)
return false;
Node* p = getPointer(pos);
p->data = n;
return true;
}
bool erase(const T& t)
{
int pos = find(t);
if(pos == -1)
return false;
if(pos == 0)
{
Node* p = head->next;
delete head;
head = p;
}
else
{
Node* pre = getPointer(pos-1);
Node* cur = pre->next;
pre->next = cur->next;
delete cur;
}
return true;
}
};