#include <iostream>
#include <algorithm>
using namespace std;
/*
静态链表: 数组实现链表的逻辑 a[x] = y: x的后继是y
1、已知链表开头元素是head, 最后一个元素的后继标记为-1, 遍历整张链表
for(int i=head; i!=-1; i=a[i]) for(p = head; p; p=p->next)
cout<<i<<" "; cout<<p->data<<" ";
2、向结点x的后面插入结点y
a[y]=a[x], a[x]=y y->next=x->next, x->next=y
3、删除x的后继
a[x]=a[a[x]] x->next=x->next->next
双向链表
struct node {
int data;
node *next, *prev;
}
1、已知p结点的位置, 删除p的后继
p->next->next->prev=p; p->next=p->next->next;
或 p->next=p->next->next; p->next->prev=p;
2、已知p结点的位置, 在p后面插入一个结点q
q->next=p->next; q->prev=p;
p->next->prev=q; p->next=q; 或 p->next=q; q->next->prev=q;
循环单链表: rear->next=head
*/
/*
动态链表
单链表为什么要有头结点?
需要找前驱的操作就统一了
*/
struct node {
int data;
node *next;
}*head, *rear;
void push_front(int x) {
node *s = (node*) malloc(sizeof (node));
s -> data = x;
s -> next = head -> next;
head -> next = s;
}
void print() {
node *p = head -> next;
cout << "head->";
while(p) {
cout << p->data << "->";
p=p->next;
}
cout << "^";
}
void push_back(int x) {
node *s = (node*) malloc(sizeof (node));
s -> data = x;
s -> next = NULL;
rear -> next = s;
rear = s;
}
void insert_back(int x, int y) {
node *p = head -> next;
while(p) {
if(p -> data == x) {
node *s = (node*) malloc(sizeof (node));
s -> data = y;
s -> next = p -> next;
p -> next = s;
return;
}
}
}
//双指针来实现删除
void erase(int x) {
node *fast, *slow;
fast = slow = head;
while(fast) {
slow = fast;
fast = fast -> next;
if(fast && fast -> data == x) {
slow -> next = fast -> next;
return;
}
}
}
//双指针实现前插操作
void insert_front(int x, int y) {
node *fast, *slow;
fast = slow = head;
while(fast) {
slow = fast;
fast = fast -> next;
if(fast && fast -> data == x) {
node *s = (node*) malloc(sizeof (node));
s -> data = y;
s -> next = fast;
slow -> next = s;
return;
}
}
}
int main() {
head = (node*) malloc(sizeof (node));
head -> next = NULL;
rear = head;
//头插法创建单链表
//push_front(1);push_front(2);push_front(3);push_front(4);push_front(5);
//尾插法创建单链表
push_back(10);
push_back(20);
push_back(30);
push_back(40);
push_back(50);
//insert_back(30, 100);
//erase(40);
insert_front(30, 100);
print();
return 0;
}
静态,动态链表
最新推荐文章于 2024-08-24 23:54:19 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)