大三今日总结.
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,实现交换p所指向的结点和它的前缀结点的顺序。
include <stdio.h>
include <stdlib.h>
typedef struct Node {
int data;
struct Node *prior;
struct Node *next;
} Node;
Node *createList(int n) {
Node *head = NULL;
Node *tail = NULL;
for (int i = 0; i < n; i++) {
int value;
scanf("%d", &value);
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = value;
newNode->prior = NULL;
newNode->next = NULL;
if (!head) {
head = newNode;
tail = newNode;
head->prior = tail;
head->next = tail;
tail->prior = head;
tail->next = head;
} else {
tail->next = newNode;
newNode->prior = tail;
newNode->next = head;
head->prior = newNode;
tail = newNode;
}
}
return head;
}
void swapNodes(Node *p) {
Node *prev = p->prior;
Node *next = p->next;
Node *prevPrev = prev->prior;
prev->next = next;
prev->prior = p;
p->next = prev;
p->prior = prevPrev;
if (prevPrev) {
prevPrev->next = p;
} else {
// 更新头指针
p->next->prior = p;
}
}
Node *findNode(Node *head, int value) {
Node *current = head;
do {
if (current->data == value) {
return current;
}
current = current->next;
} while (current!= head);
return NULL;
}
void printList(Node *head) {
Node *current = head;
do {
printf("%d", current->data);
current = current->next;
} while (current!= head);
printf("\n");
}
int main() {
int n;
if (scanf("%d", &n)!= 1) {
fprintf(stderr, "Error reading number of elements.\n");
return 1;
}
Node *head = createList(n);
int valueToSwap;
if (scanf("%d", &valueToSwap)!= 1) {
fprintf(stderr, "Error reading value to swap.\n");
return 1;
}
Node *p = findNode(head, valueToSwap);
if (p) {
swapNodes(p);
printList(head);
} else {
printf("未找到%d\n", valueToSwap);
}
return 0;
}

浙公网安备 33010602011771号