双向链表
在单向链表的基础上拓展的。
前言
双向链表难度不大,在单链表基础上拓展的。
一、基本结构
struct Node {
int data;
Node* next;//后继节点
Node* pre;//前驱节点
};
二、使用步骤
1。创造一个节点
Node* ListCreateNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
node->pre = NULL;
return node;
}
2.插入节点
Node* ListInsertNode(Node* head, int i, int v) {
Node* pro, * aft, * vtx;
int j = 0;
pro = head;
while (pro && j < i) {
pro = pro->next;
j++;
}
if (!pro) {
return NULL;
}
vtx = ListCreateNode(v);
if (!pro->next) {
pro->next = vtx;
vtx->pre = pro;
}
else {
aft = pro->next;
pro->next = vtx;
vtx->pre = pro;
vtx->next = aft;
aft->pre = vtx;
}
return vtx;
}
3.删除节点
Node* ListDeleteNode(Node* head, int i) {
Node* aft, * pro, * del;
int j = 0;
if (!head) {
return NULL;
}
if (i == 0) {//删除头节点
del = head;
head = head->next;
del->next = NULL;
free(del);
return head;
}
pro = head;
while (pro && j < i) {
j++;
pro = pro->next;
}
if (!pro && !pro->next) {
return head;
}
//此时要删除pre后面的那个节点
del = pro->next;
aft = del->next;
pro->next = aft;
aft->pre = pro;
free(del);
return head;
}
4.尾插法
Node* ListCreateListByTail(int n, int a[]) {
Node* head, * tail, * vtx;
int idx=0;
if (n <= 0) {
return NULL;
}
vtx = ListCreateNode(a[0]);
head = tail = vtx;
while (++idx < n) {
vtx = ListCreateNode(a[idx]);
tail->next = vtx;
vtx->pre = tail;
tail = vtx;
}
return head;
}
5.头插法
Node* ListCreateListByHead(int n, int* a) {
Node* head=ListCreateNode(-1), * vtx;
while (n--) {
vtx = ListCreateNode(a[n]);
vtx->next = head;
head->pre = vtx;//新增
head = vtx;
}
//vtx->next = head;//此处代码是环形链表
//head->pre = vtx;
return head;
}
6.测试函数
int main() {
int a[5] = {4,33,9,8,10};
Node* head = ListCreateListByHead(5, a);
ListPrint(head);
Node* p=ListDeleteNode(head, 2);
ListInsertNode(head, 3, 999);
ListPrint(head);
while (head->next) {
head = head->next;
}
ListPrint2(head->pre);
return 0;
}
总结
双链表会者不难,难者不会。