# 数据结构：线性结构之栈

这世间，唯有青春和梦想不可辜负。花开正好，微风不燥，扬帆起航，追逐梦想。


#### 什么是栈？

##### （一）栈的顺序存储结构

###### C语言实现顺序栈
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
#define dataType int
typedef struct {

dataType data[MAXSIZE];
int top;
}SeqStack;

//初始化顺序栈
SeqStack* Init_SeqStack(){

SeqStack* s = (SeqStack*)malloc(sizeof(SeqStack));
s->top = 0;
return s;
}

//非空判断
int IsEmpty_SeqStack(SeqStack* s){
if (s->top == 0) {
return 1;
} else{
return 0;
}
}

//判满
int IsFull_SeqStack(SeqStack* s){
if (s->top == MAXSIZE){
return 1;
} else{
return 0;
}
}

//入栈
int Push_SeqStack(SeqStack* s,dataType elem){

if (IsFull_SeqStack(s)){
return 0;
}
s->data[s->top] = elem;
s->top ++;
return 1;
}

//出栈
int Pop_SeqStack(SeqStack* s , dataType* elem){

if(IsEmpty_SeqStack(s)){
return 0;
}
s->top --;
*elem = s->data[s->top];
return 1;
}

//取栈顶元素
dataType GetTop_SeqStack(SeqStack* s){

if (IsEmpty_SeqStack(s)){
return 0;
}
return s->data[s->top - 1];
}


##### Java实现顺序栈

package cn.boom.stack;

public interface Stack<T> {
public abstract int getSize(); //获取元素个数
public abstract void push(T elem);   //入栈
public abstract T pop();       //出栈
public abstract T getTop();    //获取栈顶元素
public abstract boolean isEmpty();//判空
}

package cn.boom.stack;

public class SeqStack<T> implements Stack<T> {

private SeqList<T> seqList;

public SeqStack() {
seqList = new SeqList<T>();
}

@Override
public int getSize() {
return seqList.getSize();
}

@Override
public void push(T elem) {
}

@Override
public T pop() {
return  seqList.removeLast();
}

@Override
public T getTop() {
return seqList.getIndexOf(seqList.getSize() - 1);
}

@Override
public boolean isEmpty() {
return seqList.isEmpty();
}
}



#### （二）栈的链式存储结构

##### C语言实现链栈
#include <stdlib.h>
#include <stdio.h>
#define dataType int

typedef struct Stacknode{
dataType data;
struct Stacknode *next;
}slStacktype;

//初始化链栈
slStacktype *Init_slStacktype(){
slStacktype *top = (slStacktype *) malloc(sizeof(slStacktype));
top->next = NULL;
}

//非空判断
int IsEmpty_slStacktype(slStacktype *top){
if (top->next == NULL) {
return 1;
} else {
return 0;
}
}

//入栈
int Push_slStacktype(slStacktype *top, dataType elem) {

slStacktype *s = (slStacktype *) malloc(sizeof(slStacktype));
//malloc申请空间失败
if (s == NULL){
return 0;
}
s->data = elem;
s->next = top->next;
top->next = s;
return 1;
}

//出栈
int Pop_slStcaktype(slStacktype *top ,dataType *elem) {

if (!IsEmpty_slStacktype(top)) {

slStacktype *p = top->next;
*elem = p->data;
top->next = p->next;
free(p);
return 1;

} else {
return 0;
}
}

##### Java实现链栈

package cn.boom.stack;

public class LinkedListStack<T> implements Stack<T> {

}

@Override
public int getSize() {
}

@Override
public void push(T elem) {
}

@Override
public T pop() {
}

@Override
public T getTop() {
}

@Override
public boolean isEmpty() {
}
}



#### 参考文献

[1]王曙燕.数据结构与算法:人民邮电出版社


©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客