Advertisement
wendy890711

190616

Jun 16th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. class node {
  6. public:
  7. int data;
  8. node* next;
  9. };
  10.  
  11. class mystack {
  12. public:
  13. node* head;
  14. mystack() { head = new node(); head->next = NULL; }
  15. void push(int i);
  16. void list();
  17. void pop();
  18. };
  19.  
  20. void mystack::push(int i)
  21. {
  22. node* x = new node();
  23. x->data = i;
  24.  
  25. if (head->next == NULL)
  26. {
  27. head->next = x;
  28. return;
  29. }
  30.  
  31. node* p = head;
  32. while (p->next != NULL)
  33. p = p->next;
  34. x->next = p->next;
  35. p->next = x;
  36.  
  37. }
  38.  
  39. void mystack::list()
  40. {
  41. if (head->next == NULL)
  42. cout << "無資料" << endl;
  43. node* p = head;
  44. while (p->next != NULL)
  45. {
  46. p = p->next;
  47. cout << p->data << endl;
  48. }
  49. }
  50. void mystack::pop() {
  51.  
  52. if (head->next == NULL) {
  53. cout << "無資料" << endl;
  54. return;
  55. }
  56. node* current = head;
  57. node* pre = NULL;
  58.  
  59. while (current->next != NULL)
  60. {
  61. pre = current;
  62. current = current->next;
  63. }
  64.  
  65. cout << current->data << endl;
  66. delete current;
  67. pre->next = NULL;
  68. }
  69.  
  70. class myqueue {
  71. public:
  72. node* head;
  73. myqueue() { head = new node; head->next = NULL; }
  74. void enqueue(int i);
  75. void dequeue();
  76. };
  77.  
  78. void myqueue::enqueue(int i) {
  79. node* x = new node();
  80. x->data = i;
  81.  
  82. if (head->next == NULL)
  83. {
  84. head->next = x;
  85. return;
  86. }
  87.  
  88. node* p = head;
  89. while (p->next != NULL)
  90. p = p->next;
  91. x->next = p->next;
  92. p->next = x;
  93. }
  94.  
  95. void myqueue::dequeue()
  96. {
  97. if (head->next == NULL)
  98. {
  99. cout << "無資料" << endl;
  100. return;
  101. }
  102. node* current = head;
  103. node* pre = NULL;
  104.  
  105. if (current->next != NULL)
  106. {
  107. current = current->next;
  108. cout << current->next << endl;
  109. pre = current->next;
  110. delete current;
  111. head->next = pre;
  112. }
  113. }
  114.  
  115. void main()
  116. {
  117. mystack st1;
  118. st1.push(1);
  119. st1.push(2);
  120. st1.push(3);
  121. st1.list();
  122. st1.pop();
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement