/*
链表的实现(这是个很简单东西,写来测试速度
作者:吕翔宇
e-mail:630056108@qq.com
版权所有©
2018.10.18 20:11
这里留着头空
*/
#include<iostream>
template<typename T>
struct ListNode{//双向链表空间换时间,不解释
T content;
ListNode *ahead;
ListNode *next;
};
template<typename T>
class LinkList {
public:
LinkList() {
frist = new ListNode<T>;
frist->next =frist;
frist->ahead = frist;
};
~LinkList (){
ListNode<T> *tmp2 = frist;
while (tmp2->next != frist) {
tmp2 = tmp2->next;
free(tmp2->ahead);
}
delete(tmp2);
}
bool insert( T tmp, int tloc = 0) {
if (tloc > length)//等于因为length从1开始,loc从0开始
return false;
int loc = tloc;
ListNode<T> *tmp2=frist;
while (tloc-->0) {
tmp2 = tmp2->next;
tmp2->next = tmp2;
tmp2->ahead = tmp2;
}
ListNode<T> *r = new ListNode<T>;
r->content = tmp;
r->ahead = tmp2;
r->next = tmp2->next;
tmp2->next->ahead = r;
tmp2->next = r;
if (loc == length) {//尾插修正头指针
frist->ahead = r;
}
length++;
return true;
}
bool erase(int loc) {
if (loc >= length)//等于因为length从1开始,loc从0开始
return false;
ListNode<T> *tmp = frist->next;
while (loc-- > 0) {
tmp = tmp->next;
}
tmp->next->ahead = tmp->ahead;
tmp->ahead->next = tmp->next;
free(tmp);
length--;
}
void printAll() {
ListNode<T> *tmp = frist->next;
while (tmp!= frist) {
std::cout << tmp->content<<" ";
tmp = tmp->next;
}
std::cout << "\n";
}
void Union(LinkList *tmp) {
ListNode<T> *tmpN = tmp->frist->ahead;
LinkList *old = tmp, *tmpL = new LinkList;
while (tmpN != tmp->frist) {//防止内存冲突
tmpL->insert(tmpN->content);
tmpN = tmpN->ahead;
}
tmpL->printAll();
int loc = length;
ListNode<T> *backN = frist->ahead;
frist->ahead = tmp->frist->ahead;
tmp->frist->ahead->next = frist;
backN->next = tmp->frist->next;
tmp->frist->next->ahead = backN;
length += tmp->length;
tmp->frist = tmpL->frist;
//free(old);
}
T at(int loc) {
if (loc > length)
return;
ListNode<T> *tmp = frist;
while (loc-- > 0) {
tmp = tmp->next;
}
return tmp->content;
}
private:
ListNode<T> *frist;
int length;//存链表长度
};
int main() {
LinkList<int> a,b;
for (int i = 0; i < 20; i++) {
a.insert(i);
b.insert( - i);
}
a.printAll();
b.printAll();
b.erase(1);
b.printAll();
a.Union(&b);
a.printAll();
b.printAll();
system("pause");
}