Guest User

Untitled

a guest
Feb 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdlib.h>
  3.  
  4. struct LinkNode
  5. {
  6. int Val;
  7. struct LinkNode *Next;
  8. };
  9.  
  10. static int count;
  11.  
  12. void addEnd(struct LinkNode *root,int val);
  13. void removeEnd(struct LinkNode *root);
  14. struct LinkNode* reverse(struct LinkNode *root);
  15. void display(struct LinkNode *root);
  16.  
  17. /*
  18. output:
  19. 0 -> 1 -> 2 -> 3
  20. 3 -> 2 -> 1 -> 0
  21. 3 -> 2 -> 1
  22. */
  23. int main(void)
  24. {
  25. struct LinkNode *root = (struct LinkNode*)malloc(sizeof(struct LinkNode));
  26. count = 0;
  27.  
  28. root->Val = 0;
  29. addEnd(root,1);
  30. addEnd(root,2);
  31. addEnd(root,3);
  32. display(root);
  33.  
  34. root = reverse(root);
  35. display(root);
  36.  
  37. removeEnd(root);
  38. display(root);
  39.  
  40. getchar();
  41. }
  42.  
  43. void addEnd(struct LinkNode *root,int val)
  44. {
  45. struct LinkNode *cur,*newNode;
  46.  
  47. cur = root;
  48. newNode = (struct LinkNode*)malloc(sizeof(struct LinkNode));
  49.  
  50. newNode->Val = val;
  51. for(size_t i = 0; i < count; i++)
  52. {
  53. cur = cur->Next;
  54. }
  55. cur->Next = newNode;
  56. count++;
  57. }
  58.  
  59. void removeEnd(struct LinkNode *root)
  60. {
  61. struct LinkNode *cur;
  62. cur = root;
  63.  
  64. for(size_t i = 0; i < count; i++)
  65. {
  66. cur = cur->Next;
  67. }
  68. count--;
  69. free(cur);
  70. }
  71.  
  72. struct LinkNode* reverse(struct LinkNode *root)
  73. {
  74. struct LinkNode *prev,*cur,*next;
  75.  
  76. cur = root;
  77.  
  78. for(size_t i = 0; i < count + 1; i++)
  79. {
  80. next = cur->Next;
  81. cur->Next = prev;
  82. prev = cur;
  83. cur = next;
  84. }
  85.  
  86. return prev;
  87. }
  88.  
  89. void display(struct LinkNode *root)
  90. {
  91. struct LinkNode *cur;
  92.  
  93. cur = root;
  94.  
  95. for(size_t i = 0; i < count + 1; i++)
  96. {
  97. if (i == count) {
  98. printf("%d\n",cur->Val);
  99. } else
  100. {
  101. printf("%d -> ",cur->Val);
  102. }
  103.  
  104. cur = cur->Next;
  105. }
  106. }
Add Comment
Please, Sign In to add comment