算法与数据结构

include <stdio.h>

include <stdlib.h>

typedef struct Node {
int data;
struct Node *prior;
struct Node *next;
} Node;

// 创建双向循环链表
Node* createList(int arr[], int n) {
if (n == 0) return NULL;

Node *head = (Node*)malloc(sizeof(Node));
head->data = arr[0];
head->prior = head;
head->next = head;

Node *tail = head;

for (int i = 1; i < n; i++) {
    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = arr[i];
    
    // 插入到链表尾部
    newNode->prior = tail;
    newNode->next = head;
    tail->next = newNode;
    head->prior = newNode;
    
    tail = newNode;
}

return head;

}

// 查找指定值的节点
Node* findNode(Node *head, int value) {
if (head == NULL) return NULL;

Node *current = head;
do {
    if (current->data == value) {
        return current;
    }
    current = current->next;
} while (current != head);

return NULL;

}

// 交换节点和它的前驱节点
void swapWithPrior(Node *p) {
if (p == NULL || p->prior == p) return; // 空链表或只有一个节点

Node *q = p->prior; // p的前驱节点

// 如果只有两个节点,交换后需要更新关系
if (p->next == q && q->prior == p) {
    // 只有两个节点的情况
    p->prior = p;
    p->next = p;
    q->prior = q;
    q->next = q;
    
    p->prior = q;
    p->next = q;
    q->prior = p;
    q->next = p;
    return;
}

// 一般情况:交换q和p
Node *q_prior = q->prior; // q的前驱
Node *p_next = p->next;   // p的后继

// 更新q_prior的next指向p
q_prior->next = p;
p->prior = q_prior;

// 更新p_next的prior指向q
p_next->prior = q;
q->next = p_next;

// 更新p和q之间的关系
p->next = q;
q->prior = p;

}

// 打印链表
void printList(Node *head) {
if (head == NULL) return;

Node *current = head;
do {
    printf("%d", current->data);
    current = current->next;
} while (current != head);
printf("\n");

}

// 释放链表内存
void freeList(Node *head) {
if (head == NULL) return;

Node *current = head;
Node *temp;

do {
    temp = current;
    current = current->next;
    free(temp);
} while (current != head);

}

int main() {
int n;
scanf("%d", &n);

int *arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

int target;
scanf("%d", &target);

// 创建双向循环链表
Node *head = createList(arr, n);

// 查找目标节点
Node *p = findNode(head, target);

if (p == NULL) {
    printf("未找到%d\n", target);
} else {
    // 交换p和它的前驱节点
    swapWithPrior(p);
    
    // 如果交换的是头节点,需要更新头指针
    if (p == head) {
        head = p->prior;
    }
    
    // 输出结果
    printList(head);
}

// 释放内存
freeList(head);
free(arr);

return 0;

}

posted @ 2025-11-20 20:29  李亚宁1  阅读(7)  评论(0)    收藏  举报