一直以来以为自己知道双向链表,不就是每个节点都有两个指针,分别指向前驱和后继吗~错❌❌❌,大大的错。今天实现进程的就绪队列的时候,才发现自己数据结构的知识如此薄弱。
头节点和尾节点这两个成员是固定不变的,它们是链表固定的两个入口。新插入的结点不会替代它们的位置,
只是会插入在 head和 tail之间。就像火车一样,两头的火车头是不变的,要增加车厢,只是往中间加。
而我们的第一个元素也不是头节点,而是头节点的下一个节点。
emmm,我写了一个支持增删改查的双向链表,太navie了,但是还是要挂出来,激励自己一下,自己曾经也是写过这么?的代码,希望一年后的复试,按能写出牛逼的代码
#include<stdio.h>
#include<stdlib.h>
typedef struct double_list
{
struct double_list* pre;
struct double_list* next;
int data;
}Double_list;
void create_first_node(Double_list* first)
{
Double_list* second;
Double_list* three;
second = (Double_list*)malloc(sizeof(Double_list));
three = (Double_list*)malloc(sizeof(Double_list));
first -> pre = NULL;
first -> next = second;
first -> data = 1;
second -> pre = first;
second -> next = three;
second -> data = 2;
three -> pre = second;
three -> next = NULL;
three -> data = 3;
}
void show_double_list(Double_list* first_node)
{
Double_list * info;
info = first_node;
while(info != NULL) //哎 把while写成了if了 细心啊!!!
//这里以前写的是info->data != NULL是错的!!
{
printf("%d ",info -> data);
info = info -> next;
}
}
//队列插入的话也是插到后边吗,还是随便一个位置?
//这里按照插入到后边来计算
void add_node(Double_list* first_node,int value)
{
Double_list* info;
Double_list* add;
add = (Double_list*)malloc(sizeof(Double_list));
add -> next = NULL;
add -> data = value;
info = first_node;
while(info->next != NULL)
{
info = info ->next;
}
info ->next = add;
add -> pre = info;
}
void delete(Double_list* first_node,int number)
{
Double_list* info;
info = first_node;
while(info -> data != number)
{
info = info -> next;
}
info -> pre -> next = info -> next;
info -> next -> pre = info -> pre;
}
void modify(Double_list* first_node,int number,int value)
{
Double_list* info;
info = first_node;
int count = 1;
while(count != number)
{
info = info ->next;
count ++ ;
}
info -> data = value;
}
void find(Double_list* first_node,int number)
{
Double_list* info;
info = first_node;
int count = 1;
while(count != number)
{
info = info ->next;
count ++ ;
}
printf("\n%d\n",info -> data);
}
int main(int argc, char const *argv[])
{
Double_list* first_node;
first_node = (Double_list*)malloc(sizeof(Double_list));//这里为什么要一直加struct
create_first_node(first_node);
show_double_list(first_node);
printf("\n********\n");
add_node(first_node,4);
add_node(first_node,5);
add_node(first_node,6);
show_double_list(first_node);
delete(first_node,4);
printf("\n********\n");
show_double_list(first_node);
modify(first_node,2,42);
printf("\n********\n");
show_double_list(first_node);
find(first_node,2);
return 0;
}