![]() |
#2
YueWuSS2011-10-29 10:57
回复 楼主 zqllsszhuqi
#include<iostream>
using namespace std; class SqStack { private: typedef struct LNode { int data; struct LNode *next; }*Linklist,LNode; int count; Linklist L; public: SqStack(); SqStack(SqStack &Sq); ~SqStack(); void Push(int e); int Pop(); int empty(); }; inline SqStack :: SqStack() { count=0; L = NULL; //初始化指针成员以免出现拷贝异常 } inline SqStack :: ~SqStack() { if(!empty()) //判断栈不为空 { Linklist p = NULL; while(L) { p = L; L = L->next; delete p; } } } SqStack :: SqStack(SqStack &Sq) { count=0; if(!Sq.empty()) //原构造函数 L 没初始化,执行q = Sq.L没意义 { Linklist q; q=Sq.L; while(q) //原函数逻辑反了 { if(count==0) { L=new LNode; L->data=q->data; L->next=NULL; count++; } else { Linklist p; p=new LNode; p->data=q->data; p->next=L; L=p; count++; q=q->next; } } } else L = NULL; } void SqStack :: Push(int e) { if(count==0) { L=new LNode; L->data=e; L->next=NULL; count++; } else { Linklist p; p=new LNode; p->data=e; p->next=L; L=p; count++; } } int SqStack :: Pop() { Linklist p; int e; p=L; if(!p->next) { e=p->data; delete p; count--; } else { p = L; L=L->next; e=p->data; delete p; count--; } return e; } int SqStack :: empty() { if(count==0) return 1; else return 0; } int main() { SqStack S; SqStack T; SqStack W(T); int e; cout<<"请输入多个整数:"<<endl; cin>>e; while(e) { if(e>0) S.Push(e); else T.Push(e); cin>>e; } cout<<"正整数:"<<endl; while(!S.empty()) { int Q; Q=S.Pop(); cout<<" "<<Q; } cout<<endl; cout<<"负整数:"<<endl; while(!T.empty()) { int Q; Q=T.Pop(); cout<<" "<<Q; } cout<<endl; while(!W.empty()) { int Q; Q=W.Pop(); cout<<" "<<Q; } return 0; } [ 本帖最后由 YueWuSS 于 2011-10-29 10:59 编辑 ] |
#include<iostream>
using namespace std;
class SqStack
{
private:
typedef struct LNode
{
int data;
struct LNode *next;
}*Linklist,LNode;
int count;
Linklist L;
public:
SqStack();
SqStack(SqStack &Sq);
~SqStack();
void Push(int e);
int Pop();
int empty();
};
inline SqStack :: SqStack()
{
count=0;
}
inline SqStack :: ~SqStack()
{
}
SqStack :: SqStack(SqStack &Sq)
{
Linklist q;
int count=0;
q=Sq.L;
while(!q)
{
if(count==0)
{
L=new LNode;
L->data=q->data;
L->next=NULL;
count++;
}
else
{
Linklist p;
p=new LNode;
p->data=q->data;
p->next=L;
L=p;
count++;
}
q=q->next;
}
}
void SqStack :: Push(int e)
{
if(count==0)
{
L=new LNode;
L->data=e;
L->next=NULL;
count++;
}
else
{
Linklist p;
p=new LNode;
p->data=e;
p->next=L;
L=p;
count++;
}
}
int SqStack :: Pop()
{
Linklist p;
int e;
p=L;
if(!p->next)
{
e=p->data;
delete p;
count--;
}
else
{
L=p->next;
e=p->data;
delete p;
count--;
}
return e;
}
int SqStack :: empty()
{
if(count==0)
return 1;
else
return 0;
}
int main()
{
SqStack S;
SqStack T;
SqStack W(T);
int e;
cout<<"请输入多个整数:"<<endl;
while(cin>>e)
{
if(e>=0)
S.Push(e);
else
T.Push(e);
}
cout<<"正整数:"<<endl;
while(!S.empty())
{
int Q;
Q=S.Pop();
cout<<" "<<Q;
}
cout<<endl;
cout<<"负整数:"<<endl;
while(!T.empty())
{
int Q;
Q=T.Pop();
cout<<" "<<Q;
}
cout<<endl;
while(!W.empty())
{
int Q;
Q=W.Pop();
cout<<" "<<Q;
}
return 0;
}