有一个单向循环链表队列,从头开始报数,当报到m或者m的倍数的元素出列,根据出列的先后顺序重新组成单向循环链表。
#include <stdio.h>
#include <malloc.h>
struct node
{
int value;
node *next;
};
void createlist(node **head, int n)
{
if(head==NULL || n <= 0)
return;
*head = (node*)malloc(sizeof(node));
(*head)->value = 1;
(*head)->next = *head;
int i;
node *p = *head,*q = *head;
for(i=2;i<=n;i++)
{
p = (node*)malloc(sizeof(node));
p->value = i;
p->next = *head;
q->next = p;
q = p;
}
printf("创建的结点是:\n");
p = *head;
while(p->next != *head)
{
printf("%d\t",p->value);
p = p->next;
}
printf("%d\n",p->value);
}
void changelist(node **head, node **newhead, int m)
{
if(head == NULL || newhead == NULL || m <=0)
return;
node *prev = *head, *current = *head;
node *p,*q;
int flag = 1;//标识变换后头结点的位置
int i = 1;
while(current != NULL)
{
if(i == m)//i加到m,踢出元素,i置1
{
q = current;//缓存当前结点
prev->next = current->next;//原链表踢出元素
current = current->next;
if(flag == 1)//找到第一个满足要求元素,将其置为头结点
{
*newhead = q;
(*newhead)->next = *newhead;
p = *newhead;
flag = 0;
}
else
{
p->next = q;
p = q;
p->next = *newhead;
}
i = 1;//i置1
}
prev = current;
current = current->next;
i++;
if(prev == current)//最后一个结点
{
p->next = current;
p = current;
p->next = *newhead;
break;
}
}
}
void printlist(node *newhead)
{
if(newhead == NULL)
return;
node *p = newhead;
printf("调整后的结点是:\n");
while(p->next != newhead)
{
printf("%d\t",p->value);
p = p->next;
}
printf("%d\t",p->value);
}
int main()
{
node *head, *newhead; //创建头结点和变换后的头结点
createlist(&head,10); //创建链表
changelist(&head,&newhead,3); //变换链表
printlist(newhead); //打印变换后的链表
return 0;
}
运行结果: