栈的基本概念
栈(Stack):是只允许在一端进行插入或删除操作的线性表。
栈顶(Top):线性表允许进行插入和删除的那一端。 栈底(Bottom):固定的,不允许进行插入和删除的另一端。 空栈:不含任何元素的空表。
栈的实现
顺序栈的实现
顺序栈:利用数组存放自栈底到栈顶的数据元素,并设top指针指向当前栈顶元素的位置。
#define MaxSize 50
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int top;
}SeqStack;
void InitStack(SeqStack& s)
{
s.top = -1;
}
bool StackEmpty(SeqStack& s)
{
if (s.top == -1)
return true;
else
return false;
}
bool PushStack(SeqStack& s, ElemType x)
{
if (s.top == MaxSize - 1)
return false;
s.data[++s.top] = x;
return true;
}
bool PopStack(SeqStack& s, ElemType& x)
{
if (s.top == -1)
return false;
x = s.data[s.top--];
return true;
}
bool GetTop(SeqStack& s, ElemType& x)
{
if (s.top == -1)
return false;
x = s.data[s.top];
return true;
}
链栈的实现(不带头结点)
链栈:采用单链表存储,所有操作在单链表的表头进行。
typedef int ElemType;
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}*LinkStack;
bool InitStack(LinkStack& s)
{
s = NULL;
return true;
}
bool StackEmpty(LinkStack& s)
{
return (s == NULL);
}
bool PushStack(LinkStack& s, ElemType x)
{
LinkNode* newnode = (LinkNode*)malloc(sizeof(LinkNode));
if (newnode == NULL)
return false;
newnode->data = x;
newnode->next = s;
s = newnode;
return true;
}
bool PopStack(LinkStack& s, ElemType& x)
{
if (s == NULL)
return false;
x = s->data;
LinkNode* p=s;
s = s->next;
free(p):
return true;
}
bool GetTop(LinkStack& s, ElemType& x)
{
if (s == NULL)
return false;
x = s->data;
return true;
}
链栈的实现(带头节点)
typedef int ElemType;
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}*LinkStack;
bool InitStack(LinkStack& s)
{
s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == NULL)
return false;
s->next = NULL;
return true;
}
bool StackEmpty(LinkStack& s)
{
return (s->next == NULL);
}
bool PushStack(LinkStack& s, ElemType x)
{
LinkNode* newnode = (LinkNode*)malloc(sizeof(LinkNode));
if (newnode == NULL)
return false;
newnode->data = x;
newnode->next = s->next;
s->next = newnode;
return true;
}
bool PopStack(LinkStack& s, ElemType& x)
{
if (s->next == NULL)
return false;
x = s->next->data;
LinkNode* p = s->next;
s->next = p->next;
free(p);
return true;
}
bool GetTop(LinkStack& s, ElemType& x)
{
if (s->next == NULL)
return false;
x = s->next->data;
return true;
}
|