求职笔试题目(二)

链表一类的问题自己还是弄得不是特别熟,发现那天还是把题目做错了。今天在电脑上好好写了下。晕啊,啥时候自己也能成为一个编程达人呢。努力中,努力找工作当中。程序写在下面,这样应该对了吧。呵呵。

  1. //Josephus环问题 
  2. /*
  3. 设有total 个人围成一圈,对他们进行顺时针编号,从第start个人开始数1,数到第m个人,第m个人出局。
  4. 接着从出局人的下一个开始从1数,同样第m个人出局,最终这些人全部出局。请以下面的函数实现将出局
  5. 人的次序以双向链表形式实现。
  6. struct  node * locate(int total,int start,int m),
  7. 其中,struct node {
  8.                   int order;
  9.                   node*  left;
  10.                   node*  right;
  11. };
  12. */
  13. #define LENG sizeof(struct node)
  14. struct node
  15. {
  16.     int order;
  17.     struct node* left;
  18.     struct node* right;
  19. };
  20. //环状链表实现
  21. struct node* locate(int total, int start ,int m)
  22. {
  23.     struct node* cp1,*cp2,*head;// 创建环状链表时用到的指针
  24.     struct node* cpp1,*cpp2,*head2;//创建出局顺序的链表
  25.     struct node* p1,*p2,*fpointer;  //进行计数M 时用到的指针
  26.     int i,j,k;//循环变量
  27.     if(total<1 || start<1 || m<1)
  28.         exit(3);
  29. //开始创建环形链表队列
  30.     cp1=(struct node*)malloc(LENG);
  31.     cp1->left=cp1->right=NULL;
  32.     cp1->order=1;
  33.     head=cp2=cp1;
  34.     for(i=2;i<=total;i++)
  35.     {
  36.         cp1=(struct node*)malloc(LENG);
  37.         cp1->order=i;
  38.         cp1->right=NULL;
  39.         cp1->left=cp2;
  40.         cp2->right=cp1;
  41.         cp2=cp1;
  42.     }
  43.     cp2->right=head;
  44.     head->left=cp2; 
  45. //创建一个非环形链表用于标志出局顺序
  46.     cpp1=(struct node*)malloc(LENG);
  47.     cpp1->left=cp1->right=NULL;
  48.     cpp1->order=1;
  49.     head2=cpp2=cpp1;
  50.     for(i=2;i<=total;i++)
  51.     {
  52.         cpp1=(struct node*)malloc(LENG);
  53.         cpp1->order=i;
  54.         cpp1->right=NULL;
  55.         cpp1->left=cpp2;
  56.         cpp2->right=cpp1;
  57.         cpp2=cpp1;
  58.     }
  59.     
  60.     p1=head;
  61.     p2=head2;
  62. //将出局顺序写入新的双向链表中
  63.     for(k=1;k<start%total;k++)//第一个循环将从第start%total个人开始数
  64.     {
  65.         fpointer=p1;
  66.         p1=p1->right;
  67.     }
  68.     for(i=2;i<=total;i++)
  69.     {
  70.         for(j=1;j<m%total;j++)
  71.         {
  72.             fpointer=p1;
  73.             p1=p1->right;
  74.         }                       
  75.         p2->order=p1->order;//数到第m个人,将这个人的序列号安排在链表2的最左面元素中
  76.         p2=p2->right;       //链表2指向下一个元素
  77.         
  78.         fpointer->right=p1->right;//链表1删除掉第m个元素后,将此元素以后的首元素左指针向前移
  79.         free(p1);//将p1释放
  80.         p1=fpointer->right;//链表1指向下一个元素
  81.     }
  82. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值