LStach.h:
<span style="font-size:18px;">#include "stdafx.h"
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Node
{
ElemType elem;
struct Node* pNext;
}NODE,* PNODE;
class LStack
{
PNODE pBottom;
PNODE pTop;
public:
LStack();
void Show();
bool Push(ElemType);
bool Pop(ElemType&);
bool IsEmpty();
};
LStack::LStack()
{
pBottom=(PNODE)new NODE;
if(!pBottom)
{
cout << "------------初始化失败----------------" << endl;
return;
}
pBottom->elem=0;
pBottom->pNext=NULL;
pTop=pBottom;
/*cout << "pBottom=" << pBottom << " pBottom.elem=" << pBottom->elem << " pBottom->pNext=" << pBottom->pNext << endl;
for(int i=0;i<j;i++)
{
PNODE pNew=(PNODE)new NODE;
pNew->elem=i+1;
pNew->pNext=pTop;
cout << "pNew=" << pNew << " pNew.elem=" << pNew->elem << " pTop->pNext=" << pNew->pNext << endl;
pTop=pNew;
}
cout << "pTop=" << pTop << " pTop.elem=" << pTop->elem << " pTop->pNext=" << pTop->pNext << endl;*/
cout << "------------初始化完成----------------" << endl;
}
void LStack::Show()
{
if(IsEmpty())
{
cout << "栈为空,没有可以显示的元素。" << endl;
return;
}
PNODE pn=pTop;
//cout << (pTop->pNext!=NULL);
while(pn!=pBottom)
{
cout << pn->elem << endl;
pn=pn->pNext;
}
//cout << pn->elem << endl;
cout << "-----------------------------------" << endl;
}
bool LStack::Push(ElemType elem)
{
//pNew=(PNODE)new NODE;
PNODE pNew=(PNODE)new NODE;
if(!pNew)
{
cout << "------------压入操作失败----------------" << endl;
return false;
}
pNew->elem=elem;
pNew->pNext=pTop;
//cout << "pNew=" << pNew << " pNew.elem=" << pNew->elem << " pTop->pNext=" << pNew->pNext << endl;
pTop=pNew;
return true;
}
bool LStack::Pop(ElemType& elem)
{
if(IsEmpty())
{
cout << "栈为空,没有可以压出的元素。" << endl;
return false;
}
else
{
elem=pTop->elem;
//cout << "压出的元素是:" << elem << endl;
PNODE p=pTop;
pTop=pTop->pNext;
delete p;
p=NULL;
}
return true;
}
bool LStack::IsEmpty()
{
if(pBottom==pTop)
return true;
else
return false;
}</span>
main:
<span style="font-size:18px;">// LStack.cpp : Defines the entry point for the console application.
//
#include "LStack.h"
using namespace std;
int TenToBin(int i);
int main(void)
{
LStack* ls=(LStack*)new LStack();
ls->Push(100);
ls->Push(54);
ls->Push(3);
ls->Show();
ElemType et=0;
ls->Pop(et);
ls->Show();
/*ls->Push(100);
ls->Show();
ElemType elem;
ls->Pop(elem);
ls->Show();*/
ElemType ei=54;
//cout << 27/2 << endl;
TenToBin(ei);
system("pause");
return 0;
}
int TenToBin(int i)
{
if(i<0)
{
cout << "传入的值是负数" << endl;
return 0;
}
LStack* ls=(LStack*)new LStack();
while(!i==0)
{
ls->Push(i%2);
cout << "Push:" << i%2 << endl;
i=i/2;
}
//ls->Push(i%2);
//PNODE pn=NULL;
ElemType elem;
while(!ls->IsEmpty())
{
ls->Pop(elem);
cout << elem;
}
cout << endl;
return 0;
}</span>