#include<stdio.h>
#include<stdlib.h>
//链栈练习LiStack
#define MaxSize 100
#define ElemType int
//带头结点的单链表
/*
头结点之后即为栈顶在头结点之后进行操作
栈空:s->next=NULL
栈满:不存在
进栈:头插法
退栈:删除头结点之后的节点
*/
typedef struct linknode {
ElemType data;
struct linknode *next;
}LiStack;
void Init(LiStack *&s)
{
s = (LiStack *)malloc(sizeof(LiStack));
s->next = NULL;
}
//销毁,要删除所有节点包括头结点
void Destroy(LiStack *&s)
{
LiStack *p = s, *q = s->next;
while (q != NULL)
{
free(p);
p = q;
q = q->next;
}
free(p);//此时p指向尾节点,要释放
}
bool Empty(LiStack *s)
{
return(s->next == NULL);
}
void Push(LiStack *&s, ElemType e)
{
LiStack *p, *r;
r = (LiStack *)malloc(sizeof(LiStack));
r->data = e;
r->next = s->next;
s->next = r;
}
bool Pop(LiStack *&s, ElemType e)
{
if (s->next == NULL)
return false;
LiStack *p = s->next;
e = p->data;
s->next = p->next;
free(p);
return true;
}
bool GetTop(LiStack *&s, ElemType e)
{
if (s->next == NULL)
return false;
LiStack *p = s->next;
e = p->data;
return true;
}
//练习:括号匹配
bool Match(char st[],int n)
{
LiStack *s, *p;
int i=0, j;
char e;
bool match = true;
Init(s);
while (i < n&&match)
{
if (st[i] == '(')
{
Push(s, st[i]);
}
else {
if (GetTop(s, e) == true)
{
if (e == '(')
{
Pop(s, e);
}
else
match = false;
}
else
{
return false;
}
}
i++;
}
return (Empty(s) == true);
}
栈表定义练习
最新推荐文章于 2022-10-29 17:46:56 发布