#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
T data;
Node *pre;
Node *next;
Node* head;
Node* rear;
public:
void inin()
{
head = 0;
rear = 0;
}
void add(T pdata) //加入新的node到list最後面
{
Node *current = new Node;
current->data = pdata;
current->next = 0;
current->pre = 0;
if(isEmpty())
{
head = current;
rear = head;
}
else
{
rear->next = current;
current->pre = rear;
rear = current;
}
}
void remove(int n) //刪除特定位置的node from:1~n
{
if(isEmpty())
{
cout<<"List is empty now."<<endl;
}
else
{
Node* current = 0;
Node* current2 = 0;
Node* current3 = 0;
int cnt=1;
for(current=head;current!=0&&cnt!=n;current=current->next)
{
cnt++;
}
if(cnt==n)
{
if(cnt==1)
{
head = current->next;
head->pre = 0;
}
else if(cnt==size())
{
rear = current->pre;
rear->next = 0;
}
else
{
current2 = current->pre;
current3 = current->next;
current2->next = current3;
current3->pre = current2;
}
delete current;
}
else
{
cout<<"Error"<<endl;
}
}
}
T at(int n) //取得特定位置的data value
{
Node* current = 0;
int cnt =1;
for(current=head;current!=0&&cnt!=n;current=current->next)
{
cnt++;
}
return current->data;
}
int size() //取得list大小
{
Node* current = 0;
int cnt =0;
for(current=head;current!=0;current=current->next)
{
cnt++;
}
return cnt;
}
int isEmpty() //判斷list是不是空的,0代表不是空的,非0代表空的
{
if(head==0)
return 1;
else
return 0;
}
void show() //依序顯示目前node的data
{
if(isEmpty())
{
cout<<"EMPTY"<<endl;
}
else
{
Node* current = 0;
for(current=head;current!=0;current=current->next)
{
cout<<current->data<<" ";
}
cout<<endl;
}
}
};
int main()
{
int tmp;
Node <int>TwoLink;
TwoLink.inin();
TwoLink.add(1);
TwoLink.add(2);
TwoLink.add(3);
TwoLink.show();
cout<<"Size= "<<TwoLink.size()<<endl;
tmp = TwoLink.at(3);
cout<<"tmp= "<<tmp<<endl;
TwoLink.remove(3);
TwoLink.show();
return 0;
}
留言列表