每日一题Day31

双向循环链表中结点的交换

描述

利用双向循环链表表示一个整数序列,指定一个结点位置用p指向该结点,交换p所指向的结点及其前驱结点的顺序。

输入

多组数据,每组数据有三行,第一行为链表的长度n,第二行为链表的n个元素(元素之间用空格分隔),第三行为p所指向的结点位置。当n=0时输入结束。

输出

对于每组数据分别输出一行,依次输出交换结点顺序后的链表元素,元素之间用空格分隔。

样例输入1 

5
44 11 22 33 55
3
6
22 33 11 66 44 55
6
0

样例输出1

44 22 11 33 55
22 33 11 66 55 44

解答:创建循环链表。根据给定位置,修改该结点和前驱的指针指向。注意链表长度为1时,不用做任何修改。

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
	int data;
	struct node *prior;
	struct node *next;
} Node,*List;

void Create(List &L,int n)
{
	Node *p,*rear;
	L=(Node *)malloc(sizeof(Node));
	L->prior=L;
	L->next=L;
	rear = L;
	while(n--)
	{
		p=(Node *)malloc(sizeof(Node));
		scanf("%d",&p->data);
		p->next=rear->next;
		rear->next=p;
		p->prior=rear;
		p->next->prior=p;
		rear=p;
	}
}

void Exchange(List &L,int index)
{
	Node *p;
	p=L;
	while(index--)
	{
		p=p->next;
	}
	p->prior->next=p->next;
	p->prior->prior->next=p;
	p->next=p->prior;
	p->prior=p->prior->prior;
	p->next->prior=p;
	p->next->next->prior=p->next;
}

int main()
{
	int n,index;
	List L;
	Node *p;
	while(1)
	{
		scanf("%d",&n);
		if(n==0)
			break;
		Create(L,n);
		scanf("%d",&index);
		if(n==1)
		{
			printf("%d\n",L->next->data);
			continue;
		}
		Exchange(L,index);
		p=L->next;
		int first=1;
		while(p!=L)
		{
			if(first)
			{
				printf("%d",p->data);
				first=0;
			}
			else
			{
				printf(" %d",p->data);
			}
			p=p->next;
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZLambert/article/details/81628070
今日推荐