链表

来源:互联网 发布:windows photos 卸载 编辑:程序博客网 时间:2024/06/14 17:04

hdu 1216 Assistance Require

主要是为了学习链表才做这题。

利用了链表这个数据结构,因为数组的删除需要大量的移位,对这题而言是必定超时的。

#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int temp[3010];
struct node
{
int val;
node *next;
};
node *head;
void creatnodelist()
{
node *q;
head=new node;
q=head;
for(int i=2;i<=40010;i++)
{
node *p=new node;
p->val=i;
q->next=p;
q=p;
}
q->next=NULL;
}
void getsolve()
{
creatnodelist();
node *p=head;
int cnt=1;
while(p->next!=NULL)
{
int u=p->next->val;
temp[cnt++]=u;
if(cnt==3001) break;
int ans=0;
node *v=p;
while(v->next!=NULL)
{
if(ans%u==0&&ans!=1&&ans!=0)
{
node *t=v->next;
if(t->next!=NULL)

t=t->next;
v->next=t;
ans++;
}
}
v=v->next;
ans++;
}
p=p->next;
}
}
int main()
{
getsolve();
int n;
while(scanf("%d",&n)!=EOF&&n)
{
printf("%d\n",temp[n]);
}
return 0;
}

链表创建与测试:

#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
struct node
{
int val;
node *next;
};
node *head;
void creatnodelist()
{
node *q;
head=new node;
q=head;
for(int i=1;i<=50000;i++)
{
node *p=new node;
p->val=i;
q->next=p;
q=p;
}
q->next=NULL;//链表尾部
}
void test()
{
node *p=head;
while(p->next!=NULL)
{
  //if(p->next->val==31) break;
  printf("%d ",p->next->val);
  p=p->next;
}
}
void getsolve()
{
creatnodelist();
    test();
}
int main()
{
getsolve();
return 0;
}


原创粉丝点击