mbah_bejo

Last Man Standing(ORI)

Mar 5th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct node {
  4. int num;
  5. struct node *next;
  6. } Node, *NodePtr;
  7. int main() {
  8. NodePtr curr, linkCircular(int), playGame(NodePtr, int, int);
  9. int n, m;
  10. //do {
  11. printf("Enter number of children and length of count-out: ");
  12. scanf("%d %d", &n, &m);
  13. //} while (n < 1 || m < 1);
  14. curr = linkCircular(n); //link children in a circular list
  15. curr = playGame(curr, n, m); //eliminate n-1 children
  16. printf("The winning child: %d\n", curr -> num);
  17. } //end main
  18.  
  19. NodePtr makeNode(int n) {
  20. NodePtr np = (NodePtr) malloc(sizeof (Node));
  21. np -> num = n;
  22. np -> next = NULL;
  23. return np;
  24. } //end makeNode
  25.  
  26. NodePtr linkCircular(int n) {
  27. //link n children in a circular list; return pointer to first child
  28. NodePtr first, np, makeNode(int);
  29. int h,c;
  30. first = np = makeNode(1); //first child
  31. for ( h = 2; h <= n; h++) { //link the others
  32. np -> next = makeNode(h);
  33. np = np -> next;
  34. }
  35. np -> next = first; //set last child to point to first
  36. return first;
  37. } //end linkCircular
  38.  
  39. NodePtr playGame(NodePtr first, int x, int m) {
  40. NodePtr prev, curr = first,temp=first;
  41. int h,c;
  42. //eliminate x children
  43.  
  44. for ( h = 1; h <= x; h++) {
  45. //curr is pointing at the first child to be counted;
  46. //count m-1 more to get to the mth child
  47. for ( c = 1; c < m+1; c++) {
  48. prev = curr;
  49. //printf("%d_",curr->num);
  50. curr = curr -> next;
  51. }
  52. temp=temp->next;
  53. if(h<x)
  54. printf("%d ",curr->num);
  55. else
  56. printf("@\n");
  57. //printf("\n");
  58. //delete the mth child
  59. prev->next  = curr->next;
  60. free(curr);
  61. curr=temp;
  62. //curr = prev; //set curr to the child after the one eliminated
  63. }
  64. return curr;
  65. } //end playGame
Add Comment
Please, Sign In to add comment