给定一组数存入链表中 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);
}
本文介绍了一种链表旋转算法,通过在头节点后插入新节点并释放最右边节点的方式,实现链表数值的右移。提供了完整的C语言代码实现,包括创建链表、打印链表、旋转链表和计算链表长度等功能。
844

被折叠的 条评论
为什么被折叠?



