11.25
include
using namespace std;
struct Node{
int data;
Node *prior;
Node *next;
Node(int val):data(val),prior(nullptr),next(nullptr){}
};
Node *createList(int n,int arr[]){
if(n==0)return nullptr;
Node *head=new Node(arr[0]);
Node *curr=head;
for(int i=1;i<n;++i){
Node *newNode=new Node(arr[i]);
curr->next=newNode;
newNode->prior=curr;
curr=newNode;
}
curr->next=head;
head->prior=curr;
return head;
}
void swapWithPrior(Node&head,Nodep){
if(!head||!p||head->nexthead)return;
Node *pre=p->prior;
if(prehead){
Node prePre=pre->prior;
Node pNext=p->next;
prePre->next=p;
p->prior=prePre;
p->next=pre;
pre->prior=p;
pre->next=pNext;
pNext->prior=pre;
head=p;
}
else{
Node * prePre=pre->prior;
Node pNext=p->next;
prePre->next=p;
p->prior=prePre;
p->next=pre;
pre->prior=p;
pre->next=pNext;
pNext->prior=pre;
}
}
Node * findNode(Nodehead ,int target){
if(!head)return nullptr;
Node *curr=head;
do{
if(curr->data==target)return curr;
curr=curr->next;
}while(curr!=head);
return nullptr;
}
void printList(Node head){
if(!head)return ;
Node * curr=head;
do{
cout<
curr=curr->next;
}while(curr!=head);
cout<<endl;
}
void freeList(Node
if(!head)return ;
Node *curr=head;
Node *nextNode;
do{
nextNode=curr->next;
delete curr;
curr=nextNode;
}while(curr!=head);
}
int main(){
int n;
cin>>n;
int *arr=new int[n];
for(int i=0;i<n;++i){
cin>>arr[i];
}
int target;
cin>>target;
Node *head=createList(n,arr);
delete[]arr;
Node *p=findNode(head,target);
if(!p){
cout<<"未找到"<<target<<endl;
freeList(head);
return 0;
}
swapWithPrior(head,p);
printList(head);
freeList(head);
return 0;
}

浙公网安备 33010602011771号