zoukankan      html  css  js  c++  java
  • 约瑟夫问题

     1 #include<stdio.h>  
    2 #include<stdlib.h>
    3 struct node
    4 {
    5 int num;
    6 struct node *next;
    7 };
    8 int n,k;
    9 struct node * input(int n)
    10 {
    11 int i;
    12 struct node *head,*tail,*p;
    13
    14 p = (struct node *)malloc(sizeof(struct node));
    15 p->next = NULL;
    16 tail = head = p;
    17 p->num = 1; //循环链表,头指针数据存在
    18 for(i = 1;i < n;i++)
    19 {
    20 p = (struct node *) malloc (sizeof(struct node));
    21 p->num = i + 1;
    22 p->next = NULL;
    23 tail->next = p;
    24 tail = tail->next;
    25 }
    26 tail->next = head; //头尾相连构成环
    27 return head;
    28 }
    29 int del(struct node *head,int n,int k)
    30 {
    31 struct node *p,*q;
    32 int i=0,count = 0;
    33 p=head;
    34 while(p->next != head) //这个地方啥意思我有点忘了。或许是它有一个以上的节点?
    35 {
    36 p = p->next; //答:让他指向尾指针!!!!!,否则永远跨国一个。
    37 } //一开始的时候我是用的count = 1,然后用p直接指向头结点。后来发现当他是输入2 1 的时候结果会发生错误
    38 while(i<n-1)
    39 {
    40 q=p->next;
    41 count++;
    42 if((count) %k == 0)
    43 {
    44 p->next = q->next;
    45
    46 i++;
    47 }
    48 else p=q;
    49
    50
    51 }
    52 return p->num;
    53 }
    54 int main()
    55 {
    56 struct node* head;
    57 int j;
    58 scanf("%d %d",&n,&k);
    59 head = input(n);
    60 j = del(head,n,k);
    61 printf("%d",j);
    62 return 0;
    63 }
  • 相关阅读:
    面向对象设计原则之接口隔离原则
    面向对象设计原则之开闭原则
    [OOD]违反里氏替换原则的解决方案
    错误程序
    error: ‘for’ loop initial declarations are only allowed in C99 mode
    函数模板
    查找
    队列类模板
    栈类模板
    单链表的结点类模板
  • 原文地址:https://www.cnblogs.com/0803yijia/p/2364056.html
Copyright © 2011-2022 走看看