Advertisement
wendy890711

連結序列

Jun 3rd, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. // ConsoleApplication1.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. using namespace std;
  7.  
  8.  
  9. class node{
  10. public:
  11. int data;
  12. node* next;
  13. };
  14.  
  15. class mystack{
  16. public:
  17. node*head;
  18. mystack(){ head = new node(); head->next = NULL; }
  19. void push(int i);
  20. void list();
  21. void pop();
  22. };
  23.  
  24. void mystack::push(int i)
  25. {
  26. node*x = new node();
  27. //x->next = NULL;
  28. x->data = i;
  29.  
  30. if (head->next == NULL)
  31. {
  32. head->next = x;
  33. return;
  34. }
  35.  
  36. node*p = head;
  37. while (p->next != NULL)
  38. p = p->next;
  39. x->next = p->next;
  40. p->next = x;
  41.  
  42. }
  43.  
  44. void mystack::list(){
  45. if (head->next == NULL){
  46. cout << "empty" << endl;
  47. return;
  48. }
  49. node *p = head;
  50. while (p->next != NULL)
  51. {
  52. p = p->next;
  53. cout << p->data << endl;
  54. }
  55.  
  56. }
  57.  
  58. void mystack::pop(){
  59.  
  60. if (head->next == NULL){
  61. cout << "無資料" << endl;
  62. return;
  63. }
  64. node*current=head;
  65. node*pre = NULL;
  66.  
  67. while (current->next != NULL)
  68. {
  69. pre = current;
  70. current = current->next;
  71. }
  72.  
  73. cout << current->data << endl;
  74. delete current;
  75. pre->next = NULL;
  76. }
  77.  
  78.  
  79. void main()
  80. {
  81. mystack st1;
  82. st1.push(1);
  83. st1.push(2);
  84. st1.push(3);
  85. st1.push(4);
  86. st1.pop();
  87. st1.pop();
  88. st1.pop();
  89. st1.pop();
  90. st1.pop();
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement