Files
2022-WangDao-CS-DS-Notes/2.3链栈——栈的链式存储.md
2022-03-28 16:49:12 +08:00

166 lines
3.2 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 链栈—— Linked Stack
### 一、链栈的定义
`链栈`:栈的`链式存储`
### 二、链栈的实现方式
实现方式:`不带头结点``带头结点`,一般带头结点比不带头结点好
不带头结点:写操作代码麻烦,要区分第一个数据和后续数据的处理
带头结点:写操作代码方便,一般用带头结点,不明确的都是带头结点的
`注`:这两种方式:只有类型描述一样,初始化不一样,
判空、入栈、出栈、取栈顶元素不一样不带头节点是s带头结点是s->next因为链栈以`链头``栈顶`
### 三、不带头结点的链栈上的操作(与不带头结点的单链表一样)
`链头``栈顶`
#### 链栈的类型描述
```C
typedef struct LNode{ //定义单链表结点类型
int data; //数据域可以是别的各种数据类型本文统一用int类型
struct LNode *next; //指针域
}LNode, *LinkStack;
```
#### 初始化
```c
//初始化
void InitStack(LinkStack &S){
S = NULL;
S->next = NULL;
}
```
#### 判栈空
```c
//判空操作
bool StackEmpty(LinkStack S){
if(S == NULL){
return true;
}else{
return false;
}
}
```
#### 入栈(与单链表插入一样)
```c
bool push(LNode *s, int x){
if(s==NULL) return false;
LNode *p = (LNode*)malloc(sizeof(LNode));
if(p==NULL) return false;
p->next = NULL;
p->data = x;
p->next = s;
s = p;
return true;
}
```
#### 出栈(与单链表删除一样)
```c
bool Delete(LNode *s){
if(s==NULL) return false;
LNode *q = s;
s->data = q->data
s = q->next;
free(q);
return true;
}
```
#### 获取栈顶元素(与单链表删除一样)
```c
//获取栈顶元素e
bool GetTop(LNode &s,Elemtype &e){
if(s == NULL) return false;
e = s->data;
return true;
}
```
### 四、带头结点的链栈上的操作
s都改为s->next类型描述和初始化例外
#### 链栈的类型描述
```C
typedef struct LNode{ //定义单链表结点类型
int data; //数据域可以是别的各种数据类型本文统一用int类型
struct LNode *next; //指针域
}LNode, *LinkStack;
```
#### 初始化
```c
//初始化
void InitStack(LinkStack &S){
S = (LNode*)malloc(sizeof(LNode));
S->next = NULL;
}
```
#### 判栈空
```c
bool StackEmpty(LinkStack S){
if(S->next == NULL){
return true;
}else{
return false;
}
}
```
#### 入栈(与单链表插入一样)
```c
bool push(LNode *s, int x){
if(s==NULL) return false;
LNode *p = (LNode*)malloc(sizeof(LNode));
if(p==NULL) return false;
p->next = NULL;
p->data = x;
p->next = s->next;
s->next = p;
return true;
}
```
#### 出栈(与单链表删除一样)
```c
bool Delete(LNode *s){
if(s==NULL) return false;
LNode *q = s->next;
s->data = q->data
s->next = q->next;
free(q);
return true;
}
```
#### 获取栈顶元素
```c
//获取栈顶元素e
bool GetTop(LNode &s,Elemtype &e){
if(s->next == NULL) return false;
e = s->next->data;
return true;
}
```