单链表的循环右移k位

来源:百度知道 编辑:UC知道 时间:2024/05/27 06:53:14
用tc实现

tc2.0运行成功
#include<stdio.h>

struct node
{
int data;
struct node *next;
};

struct node * shift(struct node *head, int k)
{
struct node *p,*q;
int i;

if(head->next==NULL)
return head;

for(i=0;i<k;i++)
{
p=head;
q=head->next;
while(q->next!=NULL)
{
p=q;
q=p->next;
}
q->next=head;
p->next=NULL;
head=q;
}
return head;
}

void main()
{
int n=10,k=2;
int i;
struct node a[10],*head,*p;
head=a;
for(a[0].data=0,i=1;i<n;i++)
{
a[i].data=i;
a[i-1].next=&(a[i]);
}
a[n].next=NULL;

head=shift(head,k);
for(i=0,p=head;i<n;i++)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}