01/10/2018, 15:04
Tự tạo lớp stack trong c++
class Node
{
public:
int data;
Node* next;
Node(int a)
{
data=a;
next=NULL;
}
};
class Stack
{
public:
int size;
Node* top;
Stack()
{
size=0;
top=NULL;
}
void push(Node node)
{
if(top==NULL)
{
top=&node;
size++;
}
else
{
node.next=this->top;
this->top=&node;
size++;
}
}
void print()
{
while(this->top!=NULL)
{
cout<<this->top->data<<endl;
this->top=this->top->next;
}
}
};
int main()
{ Stack s;
Node n1(1);
s.push(n1);
Node n2(2);
s.push(n2);
s.print();
}
Em không hiểu vì sao nó in ra số 2 liên tục, mọi người giúp em với
Bài liên quan
node
này bị tiêu hủy ngay khi rời hàm rồi, bạn lấy&node
nữa là xác định.