写在前面
使用c++完成,但应该不影响c语言使用者阅读,由于栈的数组模拟比较简单,这不再完成,只完成了链栈的常用操作
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
struct node
{
char data;
node *pre,*next;
};
struct Stack
{
node *head,*last;
int len;
Stack()//初始化
{
head=new node();
last=new node();
head->next=nullptr;
last=head;
len=0;
}
char do_top()//返回栈顶元素
{
return last->data;
}
void do_pop()//弹出栈顶元素
{
node *p=last->pre;
free(last);
last=p;
last->next=nullptr;
len--;
}
bool isempty()//判断栈是否为空
{
if(head==last)
return true;
return false;
}
void do_push(char x)//压栈
{
len++;
node *newNode = new node();
newNode->data = x;
newNode->next = NULL;
newNode->pre = last;
last->next = newNode;
last = newNode;
}
int getlen()//返回栈的大小
{
return len;
}
};
队列的实现和栈的实现差不多,只有一些细微差别,但还是感觉数组模拟方便
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
struct node
{
char data;
node *pre,*next;
};
struct Queue
{
node *head,*last;
int len;
Queue()//初始化
{
head=new node();
last=new node();
head->next=nullptr;
last=head;
len=0;
}
char do_front()//返回队首元素
{
return head->data;
}
void do_pop()//弹出队首元素
{
node *p=head->next;
free(head);
head=p;
len--;
}
bool isempty()//判断队列是否为空
{
if(head==last)
return true;
return false;
}
void do_push(char x)//进队
{
len++;
node *newNode = new node();
newNode->data = x;
newNode->next = NULL;
newNode->pre = last;
last->next = newNode;
last = newNode;
}
int getlen()//返回队列的大小
{
return len;
}
};