这是一个简单的栈类,根据先进后出原则,可是在输出数据时确先输出12,10,没有输出14,为什么?请各位大侠看下!
#include<iostream>
using namespace std;
struct Node
{
int a;
Node* next;
};
class stack
{
public:
stack(){head=NULL;};
void put(int item);
int get();
private:
Node *head;
};
void stack::put(int item)
{
Node* p=new Node;
p->a=item;
p->next=head;
head=p;
}
int stack::get()
{
do{
head=head->next;
return head->a;
}while(head);
}
int main()
{stack st;
st.put(10);
st.put(12);
st.put(14);
cout<<st.get()<<endl;
cout<<st.get()<<endl;
return 0;
}
[解决办法]
get里的循环没用,清除:
#include <iostream> using namespace std; struct Node { int a; Node* next; }; class stack { public: stack(){head=NULL;}; void put(int item); int get(); private: Node *head; }; void stack::put(int item) { Node* p = new Node; p->a = item; p->next = head; head = p; } int stack::get() { if (head) { Node *temp = head; int nret = temp->a; head = head->next; delete temp; // 用完请删除 return nret; } return -1;} int main() { stack st; st.put(10); st.put(12); st.put(14); cout << st.get() <<endl; cout << st.get() <<endl; return 0; }