# 用模板实现单链表

242人阅读 评论(0)

#include<iostream>
using namespace std;

template <class T>
struct Node
{
T _data;
Node* next;
Node(const T& d)
:_data(d)
,next(NULL)
{}
};

template <class T>
{
public:
,_tail(NULL)
{}

{
{}
{
}
else
{
while(cur)
{
del = cur;
cur = cur->next ;
delete del;
}
}
}

public:
void PushBack(const T& d);
void PopBack();
void PushFront(const T& d);
void PopFront();
void Display();
int ListLen();
void Insert(const int& pos,const T& d);
void Del_Insert(const int& pos);

private:
Node<T>* _tail;
};

template <class T>
{
{
Node<T>* cur = new Node<T>(d);
_tail = cur;
}
else
{
Node<T>* cur = new Node<T>(d);

while(tmp->next )
{
tmp = tmp->next ;
}
tmp->next = cur;
_tail = cur;
}

}

template <class T>
{
{
return ;
}
{
}
else
{
/*delete _tail;
_tail = NULL;    //只是转移了_tail的指向，使其指向了NULL，并没有改变链表最后一个节点为NULL
while(cur->next)
{
cur = cur->next;
}
_tail = cur;*/
while(cur->next)
{
_tail = cur;
cur = cur->next;
}
delete cur;
_tail->next = NULL;

}
}

template <class T>
{
{
Node<T>* cur = new Node<T>(d);
_tail = cur;
}
else
{
Node<T>* cur = new Node<T>(d);
}
}

template <class T>
{
{
return ;
}
{
}
else
{
delete cur;
}
}

template <class T>
{
while(cur )
{
cout<<cur->_data <<" ";
cur = cur->next ;
}
cout<<endl;
}
template <class T>
{
int count = 0;
while(cur)
{
count++;
cur= cur->next ;
}
return count;
}

template <class T>
void LinkList<T>:: Insert(const int& pos,const T& d)
{
int num  = pos;
if(num > ListLen()+1 )
{
cout<<"NULL 链表"<<endl;
return ;
}
else
{
Node<T>* cur = new Node<T>(d);
if(num == 1)
{
}
else
{
while(--num)
{
tmp2 = tmp1;
tmp1 = tmp1->next ;

}
cur->next = tmp1;
tmp2->next = cur;
}
}

}
template <class T>
{
int num  = pos;
{
cout<<"NULL 链表"<<endl;
return ;
}
{
}
else
{
if(num == 1)
{
delete cur;
}
else
{
while(--num)
{
tmp2 = tmp1;
tmp1 = tmp1->next ;
}
tmp2->next = tmp1->next ;
delete tmp1;

}

}
}

void test()
{
l1.PushBack (1);
l1.PushBack (2);
l1.PushBack (3);
l1.PushBack (4);
l1.PushBack (5);
l1.PopBack ();
l1.PushFront (0);
l1.PopFront ();
l1.Display ();
l1.PushFront (5);
l1.Display ();
cout<<"Listlen:"<<l1.ListLen ()<<endl;

l1.Insert (1,6);
l1.Display ();
l1.Insert (2,7);
l1.Display ();
l1.Insert (8,8);
l1.Display ();
cout<<"Listlen:"<<l1.ListLen ()<<endl;

l1.Del_Insert (1);
l1.Display ();
cout<<"Listlen:"<<l1.ListLen ()<<endl;

}

int main()
{

test();
return 0;

}
0
0

个人资料
• 访问：44613次
• 积分：1127
• 等级：
• 排名：千里之外
• 原创：69篇
• 转载：16篇
• 译文：0篇
• 评论：0条