双向链表
普通的单向链表,想要找到一个节点的直接前驱时,需要从表头一个一个查找复杂度为O(n)
所以可以设置一个双向链表降低算法的复杂度。
双向链表的定义
typedef struct DuLNode
{
int data;
struct DuLNode* Next, * perior;
};
双向链表具有对称性
p ->next->prior = p = p->prior->next;
双向链表的插入
//双向链表的插入(s)后一个节点为(p)
{
s->prior = p->prior;
s->next = p;
s->prior->next = s;
s->next->prior = s;
}
双向链表的删除
//双向链表的删除(p)
{
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
p=nullptr;
}
栈:
栈
栈的构造过程:
1.首先先创造一个结构体,里面包含头尾指针和栈的最大长度。
2.创造一个栈,首先先给base赋给一个最大内存。(当内存不够时用realloc来重新申请)
并且是头尾指针同指一个地点。
3.Push :即压栈操作。通过使*(s.top++) = *e;来达到让原来的top存入数据,并且是top上移一位的操作。
-
Pop:即出栈操作。通过使*e = *(--s.top).来达到读取数据,并且使top下移一位。
-
empty :验证s.top == s.base 是否成立即可。
-
length :s.top - s.base. (验证栈满的操作相同)。
总结:
栈的基本操作便是围绕着top指针的移动来实现的。
#include<iostream>
#include<cstdlib>
#include<cmath>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
using namespace std;
typedef char ElemType;
typedef struct
{
ElemType* base;
ElemType* top;
int stacksize;
}sqStack;
void InitStack(sqStack* s)
{
s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base)
{
exit(0);
}
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void push(sqStack* s, ElemType e)
{
if (s->top - s->base >= STACK_INIT_SIZE)
{
s->base = (ElemType*)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(ElemType));
{
if (!s->base)
{
exit(0);
}
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack* s, ElemType* e)
{
if (s->top == s->base)
{
return;
}
*e = *(--s->top);
}
int Stacklen(sqStack* s)
{
return (s->top - s->base);
}