单链表简单操作
#include <bits/stdc++.h>
using namespace std;
struct node
{
int val;
node* next;
};
void print(node* head)
{
for (node* p = head; p; p = p -> next)
cout << p -> val << " ";
cout << endl;
}
void remove_1(node* &a, node* &c)
{
a -> next = a -> next -> next;
delete c;
}
void remove_2(node* &a)
{
auto p = a;
a = a -> next;
delete p;
}
void remove_toll(node* &head, int c)
{
if (head == NULL) return;
if (head -> val == c)
{
node* p = head;
head = head -> next;
delete p;
remove_toll(head, c);
}
else remove_toll(head -> next, c);
}
void insert(node* &a, node* &b, node* &c)
{
c -> next = b;
a -> next = c;
}
int main()
{
node* head = new node(), *q = new node(), *h = new node();
head -> val = 1, q -> val = 2, h -> val = 3;
head -> next = q;
insert(head, head -> next, h);
print(head);
remove_toll(head, 1);
print(head);
return 0;
}
双链表的简单操作 (双向循环只需要将头指针等于尾指针)
#include <bits/stdc++.h>
using namespace std;
struct node
{
int val;
node *next, *prev;
};
void print(node* head)
{
for (node* p = head; p; p = p -> next)
cout << p -> val << " ";
cout << endl;
}
void remove(node* &a)
{
a -> prev -> next = a -> next;
a -> next -> prev = a -> prev;
}
void insert(node* &a, node* &b, node* &c)
{
c -> next = b, c -> prev = a;
b -> prev = c, a -> next = c;
}
int main()
{
node* head = new node(), *q = new node(), *tail = new node(), *h = new node(), *hh = new node();
head -> next = tail, tail -> prev = head;
q -> val = 1, h -> val = 2, hh -> val = 3;
insert(head, head -> next, q);
insert(q, q -> next, h);
insert(h, h -> next, hh);
print(head);
remove(hh);
print(head);
return 0;
}