您的位置:首页 > 理论基础 > 数据结构算法

链表应用3:元素位置互换之移位算法

2016-07-28 20:29 351 查看
                                                         这个题我超内存。。。。。。。。。。。大神求指导,怎样才能不超内存


顺序表应用3:元素位置互换之移位算法



Time Limit: 1000MS Memory limit: 570K


题目描述

一个长度为len(1<=len<=1000000)的顺序表,数据元素的类型为整型,将该表分成两半,前一半有m个元素,后一半有len-m个元素(1<=m<=len),借助元素移位的方式,设计一个空间复杂度为O(1)的算法,改变原来的顺序表,把顺序表中原来在前的m个元素放到表的后段,后len-m个元素放到表的前段。

注意:先将顺序表元素调整为符合要求的内容后,再做输出,输出过程只能用一个循环语句实现,不能分成两个部分。


输入

 第一行输入整数n,代表下面有n行输入;
之后输入n行,每行先输入整数len与整数m(分别代表本表的元素总数与前半表的元素个数),之后输入len个整数,代表对应顺序表的每个元素。


输出

 输出有n行,为每个顺序表前m个元素与后(len-m)个元素交换后的结果


示例输入

2
10 3 1 2 3 4 5 6 7 8 9 10
5 3 10 30 20 50 80



示例输出

4 5 6 7 8 9 10 1 2 3
50 80 10 30 20


#include <stdio.h>
#include <stdlib.h>
struct node      /***´íÎó³¬ÄÚ´æ***/
{
int data;
struct node *next;
};
void print(struct node *head);
int main()
{
int a,i,j,n,m;
scanf("%d",&a);
while(a--)
{
scanf("%d %d",&n,&m);
struct node *head,*p,*tail;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0;i<m;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}

struct node *head2,*p2,*tail2;
head2=(struct node *)malloc(sizeof(struct node));
head2->next=NULL;
tail2=head2;
for(i=0;i<n-m;i++)
{
p2=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p2->data);
p2->next=NULL;
tail2->next=p2;
tail2=p2;
}

p=head->next;
p2=head2->next;
free(head);
tail2=head2;
while(p2)
{

tail2->next=p2;
tail2=p2;
p2=p2->next;
}
while(p)
{
p2=(struct node *)malloc(sizeof(struct node));
p2->data=p->data;
p2->next=NULL;
tail2->next=p2;
tail2=p2;
p=p->next;
}
print(head2);

}
}
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p)
{
if(p->next)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息