逻辑梳理
一、队列逻辑
使用双向链表
创建中间结点,一个左指针,一个右指针
左插右删
先进先出为队列,添加结点时采用尾插法
为了对应队列的逻辑结构,删除结点时直接改变中间结点的next指针和第二个结点的pre指针即可
右插左删
先进先出为队列,添加结点时依然采用尾插法,保持逻辑的一致
同理,为了对应队列的逻辑结构,删除结点时直接改变中间结点的next指针和第二个结点的pre指针即可
二、栈逻辑
左插左删
后进先出为栈,删除结点时动右指针
右插右删
后进先出为栈,删除结点时动左指针
代码
#include<stdio.h>
#include<stdlib.h>
//肯定是双向链表
//数据集合
typedef struct LinkQueue {
int element;//当前结点的真实数据
struct LinkQueue* pre;
struct LinkQueue* next;
int size;//双端队列的数目
}Node;
/*全局变量*/
Node* middle;//中间节点的指针 类似头的作用
Node* left;//左指针
Node* right;//右指针
//操作集合
void InitQueue()
{
middle = (Node*)malloc(sizeof(Node));
middle->next = NULL;
middle->pre = NULL;
left = right = middle;
middle->size = 0;
}
void left_push(int key)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->element = key;
right->next = new_node;
new_node -> pre = right;
new_node->next = NULL;
//移动右指针
right = right->next;
middle->size++;
}
void left_pop() {
if (middle->size != 0)
{
if (right == middle)
{
Node* temp = right->pre;
right->pre = right->pre->pre;
right->pre->next = right;
free(temp);
middle->size--;
}
else
{
Node* temp = right;
right = right->pre;
right->next = NULL;
free(temp);
middle->size--;
}
}
else
{
//没有元素啦
}
}
void right_push(int key)
{
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->element = key;
left->pre = new_node;
new_node->next = left;
new_node->pre = NULL;
//移动右指针
left = left->pre;
middle->size++;
}
void right_pop() {
if (middle->size != 0)
{
if (left == middle)
{
Node* temp = left->next;
left->next = left->next->next;
left->next->pre = left;
free(temp);
middle->size--;
}
else
{
Node* temp = left;
left = left->next;
left->pre = NULL;
free(temp);
middle->size--;
}
}
else
{
//没有元素啦
}
}