本节介绍双向链表的相关操作
双向链表的情况与单链表类似,只是增加了一个前置链而已。
单向链表传送门点击打开链接
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int value;
node *pre;
node *next;
} node;
node* Double_link_creat(){
node *head,*new_node,*move;
head = (node *) malloc(sizeof(node));
head->pre = NULL;
move = head;
int x;
printf("请输入你想要建立链表中节点的个数\n");
scanf("%d",&x);
for(int i = 0;i<x+1;i++){
new_node = (node *) malloc(sizeof(node));
new_node->value = i;
//双向连接
move->next = new_node;
new_node->pre = move;
//移动到新的节点
move = new_node;
}
head = head->next;
move->next = NULL;
return head;
}
//节点内容打印
void print_link(node *head){
node *p;
p = head;
while(p->next!=NULL){
printf("节点%d\n",p->value);
p = p->next;
}
}
//返回双向链表的长度
int link_length(node *head){
node *p;
p = head;
int count=0;
while(p->next!=NULL){
p = p->next;
count++;
}
return count;
}
//双向链表的删除
node *double_link_remove(node *head,int num){
node *p,*temp1;
p = head;
while(p->value !=num &&p->next!=NULL){
p = p->next;
}
if(p==head){
temp1 = p->next;
temp1->pre = NULL;
free(p);
}else if(p->next == NULL){
p->pre->next =NULL;
free(p);
}else{
p->pre->next = p->next;
p->pre = p->next->next;
free(p);
}
return head;
}
//双向链表的插入
node *double_link_insert(node* head,int num){
node *p,*p_new;
p=head;
while(p->value<num && p->next!=NULL){
p = p->next;
}
p_new = (node *) malloc(sizeof(node));
p_new->value = num;
//当插入的元素在双向链表头部的时候
if(p==head){
p_new->next = p;
p->pre = p_new;
}else if(p->next==NULL){
//当插入元素在双向链表的末尾的时候
p->next = p_new;
p_new->pre = p;
p_new->next = NULL;
}else{
//中间的时候
p_new->next = p->next;
p->next->pre = p_new;
p->next = p_new;
p_new->pre = p;
}
return head;
}
int main(){
node* head;
head = Double_link_creat();
print_link(head);
head = double_link_insert(head,1);
print_link(head);
system("PAUSE");
return 0;
}