一.单链表
链表有若干个节点组成。节点由值的next指针组成
struct Node{ //节点的结构体
int val;
Node* next;
}
用两个数组(一个数组用来存储该节点的值,一个数组用来存储节点的next)
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, head, idx;
int e[N], ne[N];
//初始化
void init(){
head = -1;
idx = 0;
}
// 在表头插入x
void insert_head(int x){
e[idx] = x;
ne[idx] = head;
head = idx;
idx ++;
}
//在第k个点后面插入x
void insert(int k, int x){
e[idx] = x;
ne[idx] = ne[k];
ne[k] = idx ++;
}
//删除第k个点的后面的点
void del(int k){
ne[k] = ne[ne[k]];
}
int main()
{
scanf("%d", &n);
init();
while(n -- ){
char op;
int k, x;
cin >> op;
if(op == 'H'){
cin >> x;
insert_head(x);
}
else if(op == 'I'){
cin >> k >> x;
insert(k - 1, x);
}
else{
cin >> k;
if(!k) head = ne[head];
del(k - 1);
}
}
for(int i = head; i != -1; i = ne[i]) //将链表中的值输出
cout << e[i] << " ";
return 0;
}
二.双链表
双链表与单链表相比多了一个指向该节点的前驱的指针
struct Node{ //双链表中节点的结构体
int val;
Node* l;
Bode* r;
}
用三个数组(一个存放指向前驱的指针,一个存放指向后驱的指针,一个存放当前节点的值)
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, idx;
int e[N], l[N], r[N];
//初始化
void init(){
r[0] = -1;
l[-1] = 0;
idx = 1;
}
//在第k个节点后面插入x
void insert(int k, int x){
e[idx] = x;
l[idx] = k;
r[idx] = r[k];
l[r[k]] = idx;
r[k] = idx;
idx ++;
}
//删除第k个插入的数
void del(int k){
l[r[k]] = l[k];
r[l[k]] = r[k];
}
int main()
{
cin >> n;
init();
while (n -- ){
string s;
cin >> s;
int k, x;
if(s == "L"){
cin >> x;
insert(0, x);
}
else if(s == "R"){
cin >> x;
insert(l[-1], x);
}
else if(s == "D"){
cin >> k;
del(k);
}
else if(s == "IL"){
cin >> k >> x;
insert(l[k], x);
}
else{
cin >> k >> x;
insert(k, x);
}
}
for(int i = r[0]; i != -1; i = r[i]) cout << e[i] << " ";
return 0;
}
三.栈
栈:先进后出 或者 后进先出
栈比较简单,就直接看代码吧
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, hh;
int stk[N];
//压栈
void push_back(int k){
stk[++ hh] = k;
}
//弹栈
void pop_back(){
hh --;
}
//查询当前栈是否为空栈
bool empty(){
return hh == 0;
}
//返回栈顶的元素
int top(){
return stk[hh];
}
int main()
{
scanf("%d", &n);
hh = 0;
while (n -- ){
string s;
cin >> s;
int x;
if(s == "push"){
cin >> x;
push_back(x);
}
else if(s == "pop"){
pop_back();
}
else if(s == "empty"){
if(empty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
else{
cout << top() << endl;
}
}
return 0;
}
四.队列
队列:先进先出 或者 后进后出
队列和栈差不多。
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int q[N];
int l, r;
//初始化
void init(){
l = r = 0;
}
//入队
void in(int x){
q[++ r] = x;
}
//出队
void out(){
l ++;
}
//判断是否队空
bool empty(){
return l == r;
}
//返回队头元素
int top(){
return q[l + 1];
}
int main()
{
int n;
cin >> n;
while (n -- ){
string s;
int x;
cin >> s;
if(s == "push"){
cin >> x;
in(x);
}
else if(s == "pop"){
out();
}
else if(s == "empty"){
if(empty()) cout << "YES" << endl;
else cout << "NO" << endl;
}
else
cout << top() << endl;
}
return 0;
}