当日总结

7-2 双向循环链表应用
分数 20
作者 liudan
单位 石家庄铁道大学
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,实现交换p所指向的结点和它的前缀结点的顺序。

输入格式:
第一行输入元素个数,第二行输入元素值,第三行输入要交换的元素值,第四行输出结果。

输出格式:
输出交换后的结果,中间不用空格分隔,若要交换的值:4,不在数组终,则输出“未找到4”

输入样例:
在这里给出一组输入。例如:

6
1 2 3 4 5 6
6
输出样例:
在这里给出相应的输出。例如:

123465

include

using namespace std;
struct Node{
int data;
Node* prior;
Node* next;
Node(int d):data(d),prior(nullptr),next(nullptr){}
};
int main()
{
int n;
cin>>n;
Node* head=nullptr;
Node* tail=nullptr;
for(int i=0;i<n;i++)
{
int val;
cin>>val;
Node* node=new Node(val);
if(headnullptr)
{
head=node;
tail=node;
node->next=node;
node->prior=node;
}
else{
tail->next=node;
node->prior=tail;
node->next=head;
head->prior=node;
tail=node;
}
}
int target;
cin>>target;
Node* p=head;
bool found=false;
if(head!=nullptr)
{
do{
if(p->data
target)
{
found=true;
break;
}
p=p->next;
}while(p!=head);
}
if(!found)
{
cout<<"未找到"<<target<<endl;
return 0;
}
Node* q=p->prior;
if(qp)
{
cout<<"未找到"<<target<<endl;
return 0;
}
Node* r=q->prior;
Node* s=p->next;
if(r
p)
{
q->prior=p;
p->next=q;
q->next=p;
p->prior=q;
head=p;
}
else{
r->next=p;
p->prior=r;
q->prior=p;
p->next=q;
q->next=s;
s->prior=q;
if(q==head)
head=p;
}
Node* curr=head;
do{
cout<data;
curr=curr->next;
}while(curr!=head);
cout<<endl;
return 0;
}

posted @ 2025-11-28 23:48  lagranSun  阅读(22)  评论(0)    收藏  举报