C/C++数据结构与算法笔记4(栈的线性存储与链式存储)
基本函数笔记来自CSDN课程 C/C++ 数据结构与算法 (王桂林)
线性存储实现:
// mystack.h
#ifndef __MYSTAK_H__
#define __MYSTACK_H__
typedef struct __MYSTACK_H__
{
int _len;
int _top;
char * _space;
}Stack;
void iniStack(Stack * s, int size);
int isStackFull(Stack * s);
int isStackEmpty(Stack * s);
void push(Stack * s, char ch);
void pop(Stack * s);
void resetStack(Stack *s);
void clearStack(Stack *s);
#endif // MYSTACK_H
// mystack.c
#include "mystack.h"
void initStack(Stack * s, int size)
{
s->_len =size;
s->_space = (char *)malloc(sizeof(char)*s->_len);
s->_top=0;
}
int isStackFull(Stack * s)
{
return s->_top == s->_len;
}
int isStackEmpty(Stack * s)
{
return s->_top == 0;
}
void push(Stack * s, char ch)
{
s->_space[s->_top++] =ch;
}
void pop(Stack *s)
{
return s->_space[--s->_top];
}
void resetStack(Stack *s)
{
s->_top =0;
}
void clearStack(Stack *s)
{
free(s->_space)
}
// main.c
#include <stdio.h>
#include "mystack.h"
int main()
{
Stack s;
initStack(&s,100);
for(char ch = 'A'; ch<='Z'; ch++)
{
if(!isStackFull(&s))
push(&s,ch);
}
while(!isStackEmpty(&s))
printf("%c",pop(&s));
retrun 0;
}
链式存储实现:
其中push的过程类似与笔记1中头插法的思维,只要抓住栈的逻辑思想是先进后出,后进先出,忽略其物理意义情况下,可以将其看作一个逆序的链表来处理。
// mystack.h
#ifndef MYSTAK_H__
#define MYSTACK_H__
typedef struct _Node
{
char data;
struct _Node *next;
}Node;
typedef struct __Stack
{
Node * top;
}Stack;
void iniStack(Stack * s, int size);
int isStackFull(Stack * s);
int isStackEmpty(Stack * s);
void push(Stack * s, char ch);
void pop(Stack * s);
void resetStack(Stack *s);
void clearStack(Stack *s);
#endif // MYSTACK_H
// mystack.c
#include "mystack.h"
void initStack(Stack * s, int size)
{
s->top = (Node*)malloc(sizeof(Node));
s->top->next =NULL;
}
int isStackEmpty(Stack * s)
{
return s->top->next == NULL;
}
void push(Stack * s, char ch)
{
Node * cur = (Node*)malloc(sizeof(Node));
cur -> data = ch;
cur->next = s->top->next;
s->top->next = cur;
}
void pop(Stack *s)
{
Node *t =s->top->next;
char ch = t->data;
s->top->next = t->next;
free(t);
return ch;
}
void resetStack(Stack *s)
{
while(!isStackEmpty)
pop();
}
void clearStack(Stack *s)
{
resetStack(s);
free(s->top);
}
// main.c
#include <stdio.h>
#include "mystack.h"
int main()
{
Stack s;
initStack(&s);
for(char ch = 'A'; ch<='Z'; ch++)
{
push(&s,ch);
}
while(!isStackEmpty(&s))
printf("%c",pop(&s));
retrun 0;
}