Node.h
#pragma once
class Node
{
public:
int data;
Node *pNext;
Node(int x=0 , Node *pNextm = nullptr)
{
data = x;
pNext = pNextm;
};
~Node();
};
Stack.h
#pragma once
#include"Node.h"
#include<iostream>
using namespace std;
class Stack
{
private:
Node *ptop;
public:
Stack();
~Stack();
void KhoitaoStack(Stack s);
Node *Khoitaonode(int x);
bool push(Stack &s, int &x);
void Nhap();
bool pop(Stack & s, int & x);
void Xuat();
void Cau8();
};
Stack.cpp
#include "Stack.h"
Stack::Stack()
{
}
Stack::~Stack()
{
}
void Stack::KhoitaoStack(Stack s)
{
s.ptop = NULL;
}
Node * Stack::Khoitaonode(int x)
{
Node *p = new Node;
if (p == NULL)
{
cout << "\nKo du bo nho ";
}
p->data = x;
p->pNext = NULL;
return p;
}
bool Stack::push(Stack & s, int & x)
{
Node *p = Khoitaonode(x);
if (s.ptop == NULL)
{
s.ptop = p;
}
p->pNext = s.ptop;
s.ptop = p;
return true;
}
void Stack::Nhap()
{
Stack s;
KhoitaoStack(s);
int n;
int a;
cout << "\nNhap so luong pt ";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "\nNhap: ";
cin >> a;
push(s, a);
}
}
bool Stack::pop(Stack &s, int &x)
{
if (s.ptop == NULL)
{
cout << "\nStack rong ";
}
Node *p = s.ptop;
x = p->data;
s.ptop = s.ptop->pNext;
delete p;
return true;
}
void Stack::Xuat()
{
Stack s;
if (s.ptop == NULL)
{
cout << "\nStack rong ";
}
while (s.ptop!=NULL)
{
int x;
pop(s, x);
cout << " " << x;
}
}
void Stack::Cau8()
{
Stack s;
s.Nhap();
s.Xuat( );
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?