求助指针链表,删除操作炸了
查看原帖
求助指针链表,删除操作炸了
390033
_caiji_楼主2021/3/19 19:34

rt,本机样例输出了两个指针,评测全 RE,求查错

#include <cstdio>
using namespace std;
template<typename T=int>
class Linked_list{//指针链表模板 
	private:
		struct node{
			T num;
			node *l,*r;
			node(const T &num,node *l=NULL,node *r=NULL):
				 num(num),l(l),r(r){}
			node():l(NULL),r(NULL){}
			~node(){delete r;}
		} head;//以head为起点的链表 
	public:
		~Linked_list(){delete head.r;}
		node* find(const T &num){//查找一个结点,返回指针 
			for(node *i=head.r;i!=NULL;i=i->r){
				if(i->num==num) return i;
			}
			return NULL;
		}
		int findidx(const T &num){//查找一个结点,返回下标,从1开始 
			int now=1;
			for(node *i=head.r;i!=NULL;i=i->r,now++){
				if(i->num==num) return now;
			}
			return 0;
		}
		void addempty(const T &num){//初始化添加 
			node *tmp=new node(num,&head,NULL);
			head.r=tmp;
		}
		void addl(const T &num,const T &posnum){//左插 
			node *pos=find(posnum);
			node *tmp=new node(num,pos->l,pos);
			if(pos->l->r!=NULL) pos->l->r=tmp;
			if(pos->l!=NULL) 	pos->l=tmp;
		}
		void addr(const T &num,const T &posnum){//右插 
			node *pos=find(posnum);
			node *tmp=new node(num,pos,pos->r);
			if(pos->r->l!=NULL) pos->r->l=tmp;
			if(pos->r!=NULL) 	pos->r=tmp;
		}
		void del(const T &num){//删除,应该是这里出了问题 
			node *tmp=find(num);
			if(tmp==NULL) return ;
			tmp->l->r=tmp->r;
		 	tmp->r->l=tmp->l;
			delete tmp;
		}
		template<typename function>
		void run(function opt){//输出 
			for(node *i=head.r;i!=NULL;i=i->r){
				opt(i->num);
			}
		}
};
int n,m;
Linked_list<int> a;
void opt(int x){printf("%d ",x);}
int main(){
	a.addempty(1);
	scanf("%d",&n);
    for(int i=2;i<=n;i++){int pos,op;
        scanf("%d%d",&pos,&op);
        if(op==0) a.addl(i,pos);
        else a.addr(i,pos);
        //a.run(opt),puts("");
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++){int x;
        scanf("%d",&x);
        a.del(x);
        //a.run(opt),puts("");//调试 
    }
    a.run(opt);
	return 0;
}
2021/3/19 19:34
加载中...