交换双向循环链表中的指定结点及其前驱。
输入样例:
5
44 11 22 33 55
3
6
22 33 11 66 44 55
6
0
输出样例:
44 22 11 33 55
22 33 11 66 55 44
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode {
int data;
struct LNode *prior, *next;
} LNode, *LinkList;
LinkList ListInit();
void ListDestroy(LinkList *head);
void ListTailInsert(LinkList head, int x);
void ListSwap(LinkList head, int x);
void ListShow(LinkList head);
int main() {
int m;
while (scanf("%d%*c", &m) && m) {
LinkList L = ListInit();
int x;
while (m--) {
scanf("%d%*c", &x);
ListTailInsert(L, x);
}
scanf("%d%*c", &x);
ListSwap(L, x);
ListShow(L);
ListDestroy(&L);
}
return 0;
}
LinkList ListInit() {
LinkList head = (LNode *) malloc(sizeof(LNode));
head->data = 0;
head->prior = head->next = head;
return head;
}
void ListDestroy(LinkList *head) {
LNode *tmp;
(*head)->prior->next = NULL;
while (*head) {
tmp = *head;
*head = (*head)->next;
free(tmp);
}
}
void ListTailInsert(LinkList head, int x) {
LNode *newNode = (LNode *) malloc(sizeof(LNode));
newNode->data = x;
newNode->next = head;
newNode->prior = head->prior;
head->prior->next = newNode;
head->prior = newNode;
}
void ListSwap(LinkList head, int x) {
LNode *cursor = head, *previous;
while (x--) cursor = cursor->next;
previous = cursor->prior;
previous->prior->next = cursor;
cursor->prior = previous->prior;
cursor->next->prior = previous;
previous->next = cursor->next;
cursor->next = previous;
previous->prior = cursor;
}
void ListShow(LinkList head) {
for (LNode *cursor = head->next; cursor != head; cursor = cursor->next) {
printf("%d%c", cursor->data, cursor->next == head ? 10 : 32);
}
}