旋转链表C语言

给定一组数存入链表中 1 2 3 4 5 后再给出一个k=2,即让链表中的数右移。以4 5 1 2 3的形式输出。我的想法是利用循环 每次在头节点后插入一个新节点值为最右边的值 后将最右边的节点释放。
#include<stdio.h>
#include<stdlib.h>
typedef struct student{
int data;
struct student *next;
struct student *last;
}Linklist,*Linklistptr;

Linklistptr end;

Linklist *creat()
{
Linklistptr head,node;
head = (Linklistptr)malloc(sizeof(Linklist));
head->next = NULL;
end = head;
while(1){
node = (Linklistptr)malloc(sizeof(Linklist));
scanf("%d",&node->data);
if(node->data==-1) break;
node->next = end->next;
end->next = node;
node->last = end;
end = node;
}
free(node);
return head;
}

void print(Linklistptr head){
Linklistptr p = head->next;
while(p!=NULL){
printf("%d ",p->data);
p = p->next;
}
}

Linklist *rotation(Linklistptr head,int n)
{
int i,m;
m = length(head);
Linklistptr p = head;
Linklistptr node,x;
if(n>=m) n = n%m;
for(i=0;i<n;i++)
{
node = (Linklistptr)malloc(sizeof(Linklist));
node->data = end->data;
node->next = p->next;
p->next = node;
node->last = p;
end = end->last;
x = end->next;
free(x);
}
end->next = NULL;
return head;
}

int length(Linklistptr x){
Linklistptr p = x;
int count = 0;
while(p->next!=NULL){
count++;
p = p->next;
}
return count;
}

int main()
{
int n;
Linklistptr head,head1;
head = creat();
scanf("%d",&n);
head1 = rotation(head,n);
print(head1);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值