11.20
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;
}
// 交换p和其前驱节点
void swapWithPrior(Node& head, Node p) {
if (!head || !p || head->next == head) return; // 空链表或单节点链表无需交换
Node* pre = p->prior; // p的前驱节点
// 情况1:pre是头节点(此时交换后p成为新头)
if (pre == head) {
Node* prePre = pre->prior; // 原头节点的前驱(尾节点)
Node* pNext = p->next; // p的后继节点
// 更新prePre的next指针
prePre->next = p;
p->prior = prePre;
// 更新p和pre的关系
p->next = pre;
pre->prior = p;
// 更新pre的next指针(指向p的原后继)
pre->next = pNext;
pNext->prior = pre;
// 新头节点变为p
head = p;
}
// 情况2:pre不是头节点(普通情况)
else {
Node* prePre = pre->prior; // pre的前驱节点
Node* pNext = p->next; // p的后继节点
// 1. prePre 连接到 p
prePre->next = p;
p->prior = prePre;
// 2. p 连接到 pre
p->next = pre;
pre->prior = p;
// 3. pre 连接到 pNext
pre->next = pNext;
pNext->prior = pre;
}
}
// 查找目标节点
Node* findNode(Node* head, 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->data;
curr = curr->next;
} while (curr != head);
cout << endl;
}
// 释放链表内存(避免内存泄漏)
void freeList(Node* head) {
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;
}
// 交换p和其前驱节点
swapWithPrior(head, p);
// 输出结果
printList(head);
// 释放链表内存
freeList(head);
return 0;
}

浙公网安备 33010602011771号