说更新就更新,久违的更新数据结构与算法的知识。今天作者我跑步了,寒冷且干燥的天气差点没把我送走。只实现了基础的操作,书上队列和栈判断是否为空方法不同,我增加了一个length变量,两种方法都可以。
1.初始化
bool InitStack()
{
head=(Node *)malloc(sizeof(Node));
if(head==nullptr)
{
return false;
}
head->next=nullptr;
return true;
}
2.访问信息
Data GetTop()
{
return head->next->item;
}
3.出栈与入栈
bool push(Data e)
{
Node *s=(Node *)malloc(sizeof(Node));
if(s==nullptr)
{
return false;
}
s->item=e;
s->next=head->next;
head->next=s;
length++;
return true;
}
Data pop()
{
if(IsEmpty())
return -1;
Node *tmp=head->next;
Data p=tmp->item;
head->next=tmp->next;
free(tmp);
length--;
return p;
}
4.全部代码
#include
using namespace std;
template
struct Node{
Data item;
Node* next;
};
template
class LinkStack{
private:
Node* head;
int length;
public:
LinkStack()
{
length=0;
}
bool IsEmpty()
{
return length==0;
}
bool InitStack()
{
head=(Node *)malloc(sizeof(Node));
if(head==nullptr)
{
return false;
}
head->next=nullptr;
return true;
}
Data GetTop()
{
return head->next->item;
}
bool push(Data e)
{
Node *s=(Node *)malloc(sizeof(Node));
if(s==nullptr)
{
return false;
}
s->item=e;
s->next=head->next;
head->next=s;
length++;
return true;
}
Data pop()
{
if(IsEmpty())
return -1;
Node *tmp=head->next;
Data p=tmp->item;
head->next=tmp->next;
free(tmp);
length--;
return p;
}
int GetLength()
{
return length;
}
};
int main()
{
LinkStack a;
a.InitStack();
for(float i=0;i<15;i++)
a.push(i/3.5);
while(!a.IsEmpty())
{
cout<
顺序栈懒得写模板了,等会会直接传上来。