fork download
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cmath>
  4. #include <cassert>
  5. #include <iostream>
  6.  
  7. struct listNode{
  8. int data;
  9. struct listNode *nextptr;
  10. };
  11.  
  12. typedef struct listNode ListNode;
  13. typedef ListNode *ListNodePtr;
  14.  
  15. ListNodePtr create(const int W) {
  16. assert(W >= 1 && "What are you thinking ?");
  17. ListNodePtr headPtr = (ListNodePtr)malloc(sizeof(ListNode));
  18. headPtr->data = 0;
  19. headPtr->nextptr = NULL;
  20. ListNodePtr lastPtr = headPtr;
  21. for(int i=1;i<W;i++){
  22. ListNodePtr nowPtr = (ListNodePtr)malloc(sizeof(ListNode));
  23. nowPtr->data=i;
  24. nowPtr->nextptr=NULL;
  25. lastPtr->nextptr=nowPtr;
  26. lastPtr=nowPtr;
  27. }
  28. return headPtr;
  29. };
  30.  
  31. int ranX(ListNodePtr *headPtrPtr, const int W){
  32. assert(headPtrPtr != NULL && "Are you kidding me ?");
  33. assert(W >= 1 && "What are you thinking ?");
  34. ListNodePtr headPtr = *headPtrPtr;
  35. assert(headPtr != NULL && "You want too much.");
  36. int r=rand()%W;
  37. ListNodePtr lastPtr = NULL;
  38. ListNodePtr nowPtr = headPtr;
  39. for(int i=0; i<r && nowPtr->nextptr !=NULL;i++){
  40. lastPtr=nowPtr;
  41. nowPtr=nowPtr->nextptr;
  42. }
  43. int data = nowPtr->data;
  44. if (lastPtr == NULL) {
  45. *headPtrPtr = NULL;
  46. } else {
  47. lastPtr->nextptr = nowPtr->nextptr;
  48. }
  49. free(nowPtr);
  50. return data;
  51. };
  52.  
  53. int main() {
  54. const int W = 10;
  55. ListNodePtr headPtr = create(W);
  56. for (int i = 0; i < W+1; ++i) {
  57. std::cout << ranX(&headPtr, W) << std::endl;
  58. }
  59. return 0;
  60. }
  61.  
Runtime error #stdin #stdout #stderr 0s 3432KB
stdin
Standard input is empty
stdout
3
7
9
6
4
8
5
2
1
0
stderr
prog: prog.cpp:35: int ranX(ListNode**, int): Assertion `headPtr != __null && "You want too much."' failed.