链表的实现

/*
链表的实现(这是个很简单东西,写来测试速度
作者:吕翔宇
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");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值