单链表
#include<iostream>
using namespace std;
struct Node
{
int val;
Node* next;
Node():next(NULL){};
Node(int _val): val(_val),next(NULL){}
};
void print(Node* head){
for(auto p = head;p;p = p->next){
cout << p->val <<" ";
}
cout << endl;
}
int main()
{
Node* head = new Node(1);// head -> 1
auto a = new Node(2);
head->next = a;// head -> 1 -> 2
auto b = new Node(3);
a->next = b;// head -> 1 -> 2 -> 3
auto c = new Node(4);
c->next = head->next;//head->1->4->2->3
head->next = c;
c->next = c->next->next;//head->1->4->3
delete a;
//删除第一个点
auto p = head;
head = head->next;
delete p;//head->4->3
print(head);
return 0;
}
双链表
#include<iostream>
using namespace std;
struct Node
{
int val;
Node *prev,*next;
Node():prev(NULL),next(NULL){};
Node(int _val): val(_val),prev(NULL),next(NULL){}
};
void print(Node* head){
for(auto p = head;p;p = p->next)
cout << p->val <<" ";
cout << endl;
}
int main()
{
//哨兵
Node *head = new Node(),*tail = new Node();
head->next = tail,tail->prev = head;
print(head);//0 0
//第一个位置插入一个节点
auto a = new Node(1);
a->next = head->next,a->prev = head;
head->next->prev = a,head->next = a;
print(head);//0 1 0
auto b = new Node(2);
b->next = head->next,b->prev = head;
head->next->prev = b,head->next = b;
print(head);//0 2 1 0
//将节点插入到某一个节点(b)点后边
auto c = new Node(3);
c->next = b->next,c->prev = b;
b->next->prev = c,b->next = c;
//删除掉某个点(b)
b->next->prev = b->prev;
b->prev->next = b->next;
print(head);//0 3 1 0
}
循环链表
#include<iostream>
using namespace std;
struct Node
{
int val;
Node *prev,*next;
Node():prev(NULL),next(NULL){};
Node(int _val): val(_val),prev(NULL),next(NULL){}
};
void print(Node* head){
for(auto p = head->next;p != head;p = p->next)//循环链表遍历到头就是结束
cout << p->val <<" ";
cout << endl;
}
int main()
{
//哨兵 没用
Node *head = new Node(),*tail = head;
head->next = tail,tail->prev = head;
print(head);//0 0
//第一个位置插入一个节点
auto a = new Node(1);
a->next = head->next,a->prev = head;
head->next->prev = a,head->next = a;
print(head);//0 1 0
auto b = new Node(2);
b->next = head->next,b->prev = head;
head->next->prev = b,head->next = b;
print(head);//0 2 1 0
//将节点插入到某一个节点(b)点后边
auto c = new Node(3);
c->next = b->next,c->prev = b;
b->next->prev = c,b->next = c;
//删除掉某个点(b)
b->next->prev = b->prev;
b->prev->next = b->next;
print(head);//0 3 1 0
}