双向链表的实现方案
查看原帖
双向链表的实现方案
1240728
sddssd5024010楼主2024/11/30 00:17

主要是那个前驱和后继的指针容易指空,AC代码如下

#include<bits/stdc++.h>
using namespace std;
typedef struct Lnode{
	int data;
	struct Lnode* pre;
	struct Lnode* later;
}*Linklist,LNode;

Linklist p=new LNode;

void insert(int x){
	if(p->later==NULL) {
		Linklist temp=new LNode;
		temp->later=p->later;
		p->later=temp;
		temp->pre=p;
		temp->data=x;
		return;
	}
	else{
		Linklist q=p;
		while(q->later!=NULL&&q->later->data<x){
			q=q->later;
		}
		
		Linklist temp=new LNode;
		temp->pre=q;
		temp->later=q->later;
		q->later=temp;
		temp->data=x;
	}
}

void later(int x){
	Linklist q=p;
	while(q->later!=NULL&&q->later->data<=x){
		q=q->later;
	}
	if(q==NULL||q->later==NULL) cout<<"2147483647"<<endl;
	else {
		cout<<q->later->data<<endl;
	}
}

void pre(int x){
	Linklist q=p;
	while(q->later!=NULL&&q->later->data<x){
		q=q->later;
	}
	if(q==p||q->pre==NULL) cout<<"-2147483647"<<endl;
	else {
		if(q->later->data==x) cout<<q->data<<endl;
		else	cout<<q->data<<endl;
	}
}

void loc(int x){
	Linklist q=p;
	int temp=0;
	while(temp!=x&&q!=NULL){
		temp++;
		q=q->later;
	}
	 cout<<q->data<<endl;
}

void num(int x){
	Linklist q=p->later;
	int temp=1;
	while(q!=NULL&&q->data<x){
		q=q->later;
		temp++;
	}
	cout<<temp<<endl;
}
int main(){
	int n,op,x;
	cin>>n;
	p->later=NULL;
	p->pre=NULL;
	for(int i=0;i<n;i++){
		cin>>op>>x;
		if(op==5)	insert(x);
		if(op==4)	later(x);
		if(op==3)	pre(x);
		if(op==2)	loc(x);
		if(op==1)	num(x);
	}
	return 0;
}
2024/11/30 00:17
加载中...