概述:
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
详情:单链表的基本设计(C语言代码实现) - 数据结构教程 - C语言网 (dotcpp.com)
A - 约瑟夫动态链表
动态链表(工程中使用)
#include <bits/stdc++.h>
using namespace std;
struct node//定义单向链表节点
{
int data;//节点的值
node *next;//next指针,指向下一个节点
};
int main()
{
int n,m;
cin>>n>>m;
//创建链表
node *head,*p,*now,*prev;
//创建链表的头节点
head=new node;
head->data=1;//节点的值
head->next=NULL;//指向空
now=head;
//创建链表里的其他节点
for(int i=2;i<=n;i++)
{
p = new node;
p->data=i;
p->next=NULL;
now->next=p;
now=p;
}
//最后让尾节点指向头节点
now->next=head;
//上面创建链表已完成,下面开始输出答案
now=head;
while((n--)>1)
{
for(int i=1;i<m;i++)
{
prev=now;//使prev=now以便后续删除打算输出的值
now=now->next;//指向下一位
}
cout<<now->data<<" ";//输出目标值
prev->next=now->next;//跳过目标节点
delete now;//删除目标节点
now=prev->next;//新一轮的开始
}
cout<<now->data<<" ";//输出最后一个节点,不在上面防止prev最后指向空
delete now;//删除节点
return 0;
}
B - 约瑟夫静态链表
静态链表(易内存泄漏)
#include <bits/stdc++.h>
using namespace std;
const int N=105;
struct node
{
int id,next;
}e[N];
int main()
{
int n,m;
cin>>n>>m;
//创建链表
e[0].next=1;
for(int i=1;i<=n;i++)
{
e[i].id=i;
e[i].next=i+1;
}
e[n].next=e[0].next;
int now=1,prev=1;
while((n--)>1)
{
for(int i=1;i<m;i++)
{
prev=now;
now=e[now].next;
}
cout<<e[now].id<<" ";
e[prev].next=e[now].next;
now=e[now].next;
}
cout<<e[now].id<<" ";
return 0;
}
C - 约瑟夫队列实现
#include<bits/stdc++.h>
using namespace std;
queue<int>s;
int main()
{
int n,m,t=1;
cin>>n>>m;
for(int i=1;i<=n;i++) s.push(i);
while(!s.empty())
{
if(t==m){cout<<s.front()<<" ";s.pop();t=1;}
else {t++;s.push(s.front());s.pop();}
}
}
什么都不用:
#include<bits/stdc++.h>
using namespace std;
bool a[105];
int main()
{
int n,m,t=0,s=0,f=0;
cin>>n>>m;
while(f!=n)
{
++t;
if(t==n+1) t=1;
if(!a[t]) s++;
if(s==m) {s=0;cout<<t<<" ";a[t]=1;f++;}
}
}
D - 约瑟夫一维静态链表
一维实现单向链表:
#include <bits/stdc++.h>
using namespace std;
const int N=105;
int a[N];
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) a[i]=i+1;
a[n]=1;
int prev=1,now=1;
while((n--)>1)
{
for(int i=1;i<m;i++)
{
prev=now;
now=a[now];
}
cout<<now<<" ";
a[prev]=a[now];
now=a[now];
}
cout<<now<<" ";
return 0;
}
E - 高中数学概率题
#include <bits/stdc++.h>
using namespace std;
const int N=105;
int a[N];
int main()
{
int a,b,c;
cin>>a>>b>>c;
double d=c*1.0/(a*b);
printf("%.6lf\n",d);
}
F - Travel Begins
#include <iostream>
using namespace std;
int round(double c)
{
return (int)(c+0.5);
}
int main()
{
int n,k,t;
cin>>t;
while(t--)
{
cin>>n>>k;
double t=0.5-(1e-100);
if(n-(k-1)*t<=0) cout<<0<<" ";
else cout<<(int)round(n-(k-1)*t)<<" ";
if(n*2<=k) cout<<n*2<<endl;
else
cout<<k-1+(int)round(n-(k-1)*0.5)<<endl;
}
return 0;
}