一道面试题,请教答案
用户输入M,N值,从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出。写出C程序。提示:循环链表,用取余操作做.
具体怎么操作?
程序代码:#include<stdio.h>
#include<malloc.h>
typedef struct linklist
{
int data;
struct linklist *next;
}nodetype;
nodetype *cyccreate(int n)//创建链表
{
nodetype *head,*r,*p;
int i;
head=(nodetype *)malloc(sizeof(nodetype));
head->data=1;
r=head;
printf("创建一个循环链表:\n");
for(i=2;i<=n;i++)
{
p=(nodetype *)malloc(sizeof(nodetype));
p->data=i;
r->next=p;
r=p;
}
r->next=head;
return head;
}
void cycdisp(nodetype *h)//输出由h指向的单循环的所有data阈的值
{
nodetype *p=h;
printf("输出一个单循环链表\n");
if(p==NULL)
{
printf("链表为空\n");
return ;
}
while(p->next!=h)
{
printf("%4d",p->data);
p=p->next;
}
printf("%4d\n",p->data);
}
void B_shu(nodetype *head,int n,int k)
{
nodetype *q,*p=head;
int pcount=0,t=k;;//删除结点计数器
while(pcount!=(n-1))
{
k=t;
while(k!=1)
{
q=p;
p=p->next;
k--;
}
if(k==1)
{
q->next=p->next;
printf("%4d",p->data);
free(p);
pcount++;
p=q->next;
}
}
printf("%4d\n",p->data);//输出最后一个元素
free(p);//释放最后一个结点
}
void main()
{
nodetype *head;
int n,k;
printf("please input a value n:\n");
scanf("%d",&n);
head=cyccreate(n);//创建循环链表
cycdisp(head);//输出循环链表
printf("please input a value k:\n");
scanf("%d",&k);
B_shu(head,n,k);
}
这是我用循环链表做的,单链表的即不发上来了,楼主参考下哈