作业要求:
程序代码:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct node //定义链表节点结构体:数据域、指针域
{
int data;
struct node *next;
}*linklist;
linklist create_node()//创建新节点并初始化,返回节点地址
{
linklist s=(linklist)malloc(sizeof(struct node));
if(NULL==s)
return NULL;
s->data=0;
s->next=s;
return s;
}
//头插
linklist insert_head(linklist head,int element)
{
linklist s=create_node();
if(NULL==s)
return NULL;
s->data=element;
if(NULL==head)
{
head=s;
return head;
}
linklist p=head;
while(p->next!=head)
{
p=p->next;
}
s->next=head;
head=s;
p->next=head;
return head;
}
//尾插
linklist insert_rear(linklist head,int element)
{
linklist s=create_node();
if(NULL==s)
{
puts("fail");
return NULL;
}
s->data=element;
if(NULL==head)
{
head=s;
return head;
}
linklist p=head;
while(p->next!=head)
p=p->next;
p->next=s;
s->next=head;
return head;
}
//输出
void output(linklist head)
{
linklist p=head;
while(p->next!=head)
{
printf("%-3d",p->data);
p=p->next;
}
printf("%-3d\n",p->data);
}
//头删
linklist delete_head(linklist head)
{
if(NULL==head)
{
puts("empty");
return head;
}
if(head==head->next)
{
free(head);
return NULL;
}
linklist del=head;
linklist p=head;
while(p->next!=head)
p=p->next;
head=head->next;
p->next=head;
free(del);del=NULL;
return head;
}
//尾删
linklist delete_rear(linklist head)
{
if(NULL==head)
{
puts("empty");
return head;
}
if(head==head->next)
{
free(head);
return NULL;
}
linklist p=head;
while(p->next->next!=head)
p=p->next;
linklist del=p->next;
p->next=head;
free(del);del=NULL;
return head;
}
//约瑟夫环
void josephus(linklist head,int len,int m)
{
linklist p=head;
for(int i=1;i<=len;i++)
{
for(int j=1;j<=m-2;j++)
{
p=p->next;
}
linklist del=p->next;
printf("%-3d" ,del->data);
p->next=del->next;
free(del);
p=p->next;
}
puts("");
}
//排序
void simple_sort(linklist head)
{
linklist p=head;
for(p;p->next!=head;p=p->next)
{
linklist min=p;
for(linklist q=p->next;q!=head;q=q->next)
{
if(min->data > q->data)
min=q;
}
if(min!=p)
{
int t=min->data;
min->data=p->data;
p->data=t;
}
}
}
int main(int argc, const char *argv[])
{
linklist head=NULL;
int len;
printf("please input length:");
scanf("%d",&len);
// int element;
// for(int i=0;i<len;i++)
// {
// printf("please input %d element:",i+1);
// scanf("%d",&element);
// head=insert_head(head,element);//头插
// head=insert_rear(head,element);//尾插
// }
// simple_sort(head);//排序
// output(head);//输出
// head=delete_head(head);//头删
// head=delete_rear(head);//尾删
// output(head);
//代码实现约瑟夫环
for(int i=1;i<=len;i++)
{
head=insert_rear(head,i);//根据长度循环尾插输入约瑟夫环内数值;
}
output(head);//遍历
int m;
printf("please input m of the josephus:" );
scanf("%d",&m);
josephus(head,len,m);
head=delete_head(head);//头删
head=delete_head(head);
output(head);
head=delete_rear(head);//尾删
output(head);
return 0;
}
运行结果: