fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node {
  6. int key;
  7. Node *next;
  8. };
  9.  
  10. struct Stack {
  11. Node* pHead;
  12. };
  13.  
  14. Node* createNode(int data) {
  15. Node* newNode = new Node;
  16. newNode->key = data;
  17. newNode->next = nullptr;
  18. return newNode;
  19. }
  20.  
  21. bool isEmpty(Stack s) {
  22. if (s.pHead == nullptr) return true;
  23. return false;
  24. }
  25.  
  26. void push(Stack &s, int data) {
  27. Node* newNode = createNode(data);
  28. if (isEmpty(s) == true) {
  29. s.pHead = newNode;
  30. return;
  31. }
  32.  
  33. newNode->next = s.pHead;
  34. s.pHead = newNode;
  35. }
  36.  
  37. int top(Stack s) {
  38. if (isEmpty(s) == true) return 0;
  39.  
  40. return s.pHead->key;
  41. }
  42.  
  43. void pop(Stack &s) {
  44. if (isEmpty(s) == true) return;
  45.  
  46. Node* curNode = s.pHead->next;
  47. delete s.pHead;
  48. s.pHead = curNode;
  49. }
  50.  
  51. void show(Stack s) {
  52. Node* curNode = s.pHead;
  53. while (curNode != nullptr) {
  54. cout<<curNode->key<<" ";
  55. curNode = curNode->next;
  56. }
  57. }
  58.  
  59. int main() {
  60. Stack s1, s2;
  61. s1.pHead = nullptr;
  62. push(s1, 10);
  63. push(s1, 2);
  64. push(s1, 20);
  65. show(s1);
  66.  
  67. cout<<"\n";
  68. s2.pHead = nullptr;
  69. while (isEmpty(s1) == false) {
  70. push(s2, top(s1));
  71. pop(s1);
  72. }
  73.  
  74. show(s2);
  75. }
  76.  
Success #stdin #stdout 0.01s 5544KB
stdin
Standard input is empty
stdout
20 2 10 
10 2 20