
Nguyên bản được gửi bởi
crabbk
Các bác xem hộ em xem, em gọi 2 lần câu lệnh :" cout<< new_List.pop()<<"\n";
trong hàm main() mà sao kết quả in ra vẫn sai nhỉ? Các bác edit lại giúp em với. Hàm " pop() " của em có vấn đề j fải ko??
Code của bạn, đã chữa:
Code:
// Cai dat stack su dung Link-List
#include<stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
class Node
{
private:
int data;
Node* next;
public:
Node()
{
next=NULL;
};
void set_Node(int);
int get_Node();
void set_Next(Node*);
Node* get_Next();
};
void Node::set_Node(int x)
{
data=x;
}
int Node::get_Node()
{
return data;
};
void Node::set_Next(Node* a_node)
{
next=a_node;
}
Node* Node::get_Next()
{
return next;
}
class List
{
private:
Node* head;
int count;
public:
List()
{
count=0;
}
int IsEmpty();
void push(int x);
int pop();
void show_List();
};
int List::IsEmpty()
{
if (count==0)
return 1;
else return 0;
}
void List::push(int x)
{
Node *temp=new Node;
temp->set_Node(x);
if (IsEmpty()==1)
{
temp->set_Next(NULL);
head=temp;
count++;
}
else
{
temp->set_Next(head);
head=temp;
count++;
}
}
int List::pop()
{
int t;
if (!IsEmpty())
{
t=head->get_Node();
head=head->get_Next();
count--;
return t;
}
}
void List::show_List()
{
Node* temp=head;
while ( temp!=NULL)
{
cout<<temp->get_Node()<<"\n";
temp=temp->get_Next();
}
}
int main()
{
List new_List;
int i;
for (i=1;i<10;i++)
{
new_List.push(i);
}
cout<<"Lay ra 2 phan tu dau list:\n";
cout<< new_List.pop()<<"\n";
cout<<new_List.pop()<<"\n";
cout<<"In ra cac phan tu con lai:\n";
new_List.show_List();
getch();
return(0);
}
Output:
Code:
Lay ra 2 phan tu dau list:
9
8
In ra cac phan tu con lai:
7
6
5
4
3
2
1
Hàm stack::pop() còn 1 vấn đề nữa mà bạn cần phải tự giải quyết là trường hợp pop từ stack rỗng. Hàm stack::pop() bắt buộc phải trả lại một giá trị int mà khi stack rỗng thì không có giá trị nào để trả lại cả. Vì thế giải pháp có lý duy nhất trong trường hợp này là throw exception.