因为本人觉得双链表相较于单链表来说,一些基本操作会更简单,所以今天就来看一下双链表。
下面我来例举出一道题(女朋友出的):
其实这些都是一些基本操作:增删改查。
原理也比较简单,与单链表一致(甚至比单链表更好理解)
我们来直接展示代码,有需要的同学可以直接看代码,理解起来也比较方便
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int data;
struct _node *next;
struct _node *pre;
} node;
node* list(){
node *head = (node*)malloc(sizeof(node));
head->pre=NULL;
head->next=NULL;
return head;
}
//头插法
void headinsert(node *head,int number) {
node *p=(node*)malloc(sizeof(node));
p->data=number;
if(head->next){
p->pre=head;
p->next=head->next;
head->next->pre=p;
head->next=p;
}
else {
p->next=NULL;
head->next=p;
p->pre=head;
}
}
//插入
void insert(node *head){
int count=0;
node *p=head->next;
node *q=(node*)malloc(sizeof(node));
q->data=7;
q->pre=NULL;
q->next=NULL;
while(p){
count++;
if(count==3){
q->pre=p;
q->next=p->next;
p->next->pre=q;
p->next=q;
}
p=p->next;
}
}
//查找
void find(node *head,int number){
int count=0;
int f=0;
node *p=head->next;
while(p){
count++;
if(p->data==number){
f=1;
if(p->pre){
printf("%d ",count);
printf("%d ",p->pre->data);
printf("%d\n",p->next->data);
}
else {
printf("%d ",count);
printf("%d\n",p->next->data);
}
}
if(f==0&&p->data!=number&&p->next==NULL){
printf("NO\n");
}
p=p->next;
}
}
//查找并删除
void findelete(node *head,int number){
node *p=head->next;
while(p){
if(p->data==number){
p->pre->next=p->next;
p->next->pre=p->pre;
free(p);
p=p->pre;
}
p=p->next;
}
}
//删除元素number之前的第一个数字
void finddelete(node *head,int number){
node *p=head->next;
while(p){
if(p->data==number){
if(p->pre->pre){
node *t=p->pre;
p->pre->pre->next=p;
p->pre=p->pre->pre;
free(t);
}
else {
head=p;
}
}
p=p->next;
}
}
//返回此时链表的元素个数
void total(node *head){
int count=0;
node *p=head->next;
while(p){
count++;
p=p->next;
}
printf("%d\n",count);
}
void revise(node *head,int number){
node *p=head->next;
while(p){
if(p->data==number){
p->data=13;
}
p=p->next;
}
}
//打印链表
void printlist(node *head){
node *p=head->next;
while(p){
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
//清空
void freelist(node *head){
node *p=head->next;
while(p){
head=p;
free(p);
p=head->next;
}
}
int main() {
node *head = list();
headinsert(head,2);
headinsert(head,6);
headinsert(head,4);
headinsert(head,8);
headinsert(head,23);
headinsert(head,56);
insert(head);
find(head,23);
find(head,66);
findelete(head,8);
finddelete(head,7);
total(head);
revise(head,6);
printlist(head);
return 0;
}
新手英文不太好,所以定义函数的名字可能比较怪异,写的也比较简单,大家不要介意。