链表栈,简称链栈,它是用一组不连续的存储结构来存储栈元素的线性表,主要通过指针实现其线性。
1.主要掌握两个结构体。
struct node
{
datatype data;
node *next;
};
struct stack
{
node *top;
};
第一个为结点结构体,第二个为栈结构体。这里需要注意的是跟数组实现的栈的区别,即数组实现的栈顶通过int型的变量top来表征,而链栈的栈顶是指向栈的第一个结点,且通过node型的指针来实现。
2.初始化栈是给top赋值为空,即s->top == NULL;
3.对于栈主要的操作是进栈和出栈。其主要的实现代码均可参考如下代码:
#include<iostream>
using namespace std;
typedef int datatype;
struct node
{
datatype data;
node *next;
};
struct stack
{
node *top;
};
// init stack
void initstack(stack *s)
{
s->top = NULL;
}
// push stack
int push(stack *s, datatype x)
{
node *p = (node*)malloc(sizeof(node));
p->data = x;
p->next = s->top;
s->top = p;
return 0;
}
// creat stack
stack * creatstack(int n)
{
stack *p = new stack;
initstack(p);
for(int i = 0; i < n; i++)
{
datatype x;
cin >> x;
push(p, x);
}
return p;
}
// pop stack
stack * pop(stack *s, datatype data1)
{
if(s->top == NULL)
return NULL;
data1 = s->top->data;
node *p = s->top;
s->top = s->top->next;
free(p);
return s;
}
// print stack
int show(stack *s)
{
if(s->top == NULL)
return -1;
node *r = s->top;
while(s->top != NULL)
{
cout << s->top->data << ends;
s->top = s->top->next;
}
cout << endl;
s->top = r;
return 0;
}
int main()
{
stack * q = creatstack(4);
show(q);
datatype y;
pop(q, y);
show(q);
system("pause");
return 0;
}