链表

使用前,请根据自己需要更改基本数据类型:

#define L_T int

以上实现了一个以 int\text{int} 为基本数据类型的链表定义。

操作

  • insert(p,val)\text{insert}(p,val):在第 pp 个元素后插入一个值为 valval 的元素,返回值为插入的元素在链表中的位置,时间复杂度 O(n)O(n)
  • push_front(val)\text{push\_front}(val):在链表头部插入一个值为 valval 的元素,返回值为插入的元素在链表中的位置,时间复杂度 O(1)O(1)
  • push_back(val)\text{push\_back}(val):在链表尾部插入一个值为 valval 的元素,返回值为插入的元素在链表中的位置,时间复杂度 O(1)O(1)
  • remove(p)\text{remove}(p):删除第 pp 个元素,若成功删除,返回值为删除的元素的值,否则返回 INFINF,时间复杂度 O(n)O(n)
  • pop_front()\text{pop\_front}():删除首个元素,若成功删除,返回值为删除的元素的值,否则返回 INFINF,时间复杂度 O(1)O(1)
  • pop_back()\text{pop\_back}():删除末尾元素,若成功删除,返回值为删除的元素的值,否则返回 INFINF,时间复杂度 O(1)O(1)
  • get_val(p)\text{get\_val}(p):得到第 pp 个元素的值,若存在,返回值为第 pp 个元素的值,否则返回 INFINF,时间复杂度 O(n)O(n)
  • get_front()\text{get\_front}():得到首个元素的值,若存在,返回值为首个元素的值,否则返回 INFINF,时间复杂度 O(1)O(1)
  • get_back()\text{get\_back}():得到末尾元素的值,若存在,返回值为末尾元素的值,否则返回 INFINF,时间复杂度 O(1)O(1)
  • write(l,r)\text{write}(l,r):输出第 max(l,1)min(r,size)\max(l,1)\sim\min(r,size) 个元素的值,中间用一个空格隔开,输出完后有换行,其中 sizesize 为链表中的元素个数,时间复杂度 O(n)O(n)
#define L_T int
struct List{
	int tot,size;
	int nc[N];
	struct Line{
		int head,next;
		L_T val;
	}a[N],e;
	L_T INF;
	List(){
		tot=size=0;
		for(int i=1;i<N;i++)
			nc[i]=i;
		e.head=e.next=0;
		e.val=0;
		INF=0x3f3f3f3f;
	}
	int build(int p,L_T val){
		int np=nc[++tot];
		size++;
		a[np]=e;
		a[np].head=p;
		a[np].next=a[p].next;
		a[a[p].next].head=np;
		a[p].next=np;
		a[np].val=val;
		return np;
	}
	L_T del(int p){
		size--;
		nc[tot--]=p;
		a[a[p].head].next=a[p].next;
		a[a[p].next].head=a[p].head;
		return a[p].val;
	}
	int insert(int p,L_T val){
		if(p>size)
			return 0;
		int np=0;
		for(int i=0;i<p;i++)
			np=a[np].next;
		return build(np,val);
	}
	int push_front(L_T val){
		return build(0,val);
	}
	int push_back(L_T val){
		return build(a[0].head,val);
	}
	L_T remove(int p){
		if(p>size)
			return INF;
		int np=0;
		for(int i=0;i<p;i++)
			np=a[np].next;
		return del(np);
	}
	L_T pop_front(){
		if(!size)
			return INF;
		return del(a[0].next);
	}
	L_T pop_back(){
		if(!size)
			return INF;
		return del(a[0].head);
	}
	L_T get_val(int p){
		if(size<p)
			return INF;
		int np=0;
		for(int i=0;i<p;i++)
			np=a[np].next;
		return a[np].val;
	}
	L_T get_front(){
		if(!size)
			return INF;
		return a[a[0].next].val;
	}
	L_T get_back(){
		if(!size)
			return INF;
		return a[a[0].head].val;
	}
	void write(int l,int r){
		l=max(l,1);
		r=min(r,size);
		int p=0;
		for(int i=0;i<r;i++){
			p=a[p].next;
			if(i>=l-1)
				printf("%d ",a[p].val);
		}
		printf("\n");
	}
};
posted @ 2021-09-04 23:45  luckydrawbox  阅读(17)  评论(0)    收藏  举报  来源