首先链栈相比顺序栈优点就是不容易满除非没内存,可以类比链表和顺序表。以下是针对不带头结点的基本操作。
定义链栈
typedef struct LinkNode {
int data;
struct LinkNode* next;
}Stacknode;
typedef struct LinkStack {
Stacknode* top;
int len;
}Linkstack;
这里多加了一个参数用于记录当前栈中元素个数。top用于定位栈顶元素。这里对于链栈的定义和链式队列的定义方法很类似。
初始化
//初始化(不带头结点)
bool InitLinkstack(Linkstack& S)
{
S.top = NULL;
S.len = 0;
cout << "初始化完成" << endl;
return true;
}
入栈操作
//插入数据,入栈
bool Insertstack(Linkstack& S, int e)
{
Stacknode* p = new Stacknode;
p->data = e;
if (S.top==NULL)
{
p->next = NULL;
S.top = p;
S.len++;
cout << "元素入栈成功" << endl;
return true;
}
p->next = S.top;
S.top = p;
S.len++;
cout << "元素入栈成功" << endl;
return true;
}
这里入栈操作我把他们分为两种情况一种是栈空,一种栈不为空,当栈不为空时,因为栈的先进后出的性质,新入栈的元素应指向栈顶元素。栈为空时,入栈元素即为栈顶元素。
出栈操作
//出栈
bool DeleteStack(Linkstack& S)
{
if (S.len == 0)
{
cout << "当前栈空" << endl;
return false;
}
Stacknode* p = new Stacknode;
p = S.top;
int i = S.top->data;
S.top = p->next;
S.len--;
delete p;
cout << "出栈成功,出栈元素为:" << i << endl;
return true;
}
出栈操作实际就是把top指针指向top指针的下一个元素。
遍历操作
//遍历链栈
void Printlinkstack(Linkstack S)
{
Stacknode* p=S.top;
while (p!=NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
cout << "当前栈中元素个数为:" << S.len << endl;
}
测试: