C语言实现双向链表
项目已经托管到github,地址:github项目托管地址
项目语言:采用C语言实现
实现思路:使用双向链表实现,双向链表具有的单向链表所不具备的优势,那就是可以双向遍历,这对增、删操作的效率都有显著的提高。而弊端则是造成空间效率的下降,即需要额外的指针来维持双向链表之间的连接关系。链表的实现中,我们默认采用了两个哨兵节点,该两节点标识了整个链表的头部和尾部,但其数据域不存储具体数据。同样,这对于查找时,可以方便的区分链表是否到尾部而结束。但是同样会造成空间的浪费。值得注意的是,链表是逻辑结构,在逻辑思维中,我们把这样的一种结构称之为线性结构,而实际在计算机的存储过程中,并不呈现一种严格的线性关系。而是零散的内存段区域。因为内存在进行分配时,是随机的,而不是按照线性的方式进行分配,这不符合操作系统的内存管理机制。
基本实现部分:
准备工作: 为优化代码风格,我们会极力避免在源代码中采用数字进行编码,这样会使得代码的可读性大大降低,于是我们通常约定,使用宏定义来将数字定义为符号常量,这样数字变得拥有具体含义,提高代码可读性。
#ifndef TRUE
#define TRUE 1
#endif // !TRUE
#ifndef FALSE
#define FALSE 0
#endif //!FALSE
#ifndef NULL
#define NULL 0
#endif // !NULL
#ifndef NODE_NOT_FOUND
#define NODE_NOT_FOUND -1
#endif // !NODE_NOT_FOUND
#ifndef SIZE_STUDENT
#define SIZE_STUDENT sizeof(Student)
#endif // !SIZE_STUDENT
typedef unsigned int Rank;
typedef int BOOL;
typedef struct Student
{
char name[20];
int age;
struct Student *next;
struct Student *last;
}Student, *PLinkHead, *PLinkNode;
数据定义:采用学生结构体进行测试和构建。同时应该注意,我们在进行编码时,通常是需要将逻辑与操作分离,这对于可视化界面尤为重要,我们有经典性即将表现与性了代码的可读性,还大大降低日后项目维护所需要花费的成本。
实现过程
函数前向声明:
// If you want, you can remove your statements to another new header file, and create a new
// source file to realize every function.
/*
To display information about student
* @param student The student you want to display.
*/
void display(Student * student);
/*
Create a link list with head node empty.
* @return Return the head of link list created. If you have get NULL, it stands for allocate failed.
*/
PLinkHead createLinkListHeadEmpty();
/*
To insert a node into the link list.
* @param stu_node The student to insert into the link list.
* @param _link_list_head The destination inserted into.
* @return Return the state of execute result.
*/
BOOL addNodeToLinkList(Student * stu_node, PLinkHead _link_list_head);
/*
To judge whether the link list is empty.
If you have got FALSE, it will tell you the link list isn't empty.
Or The link list is empty.
* @param _link_head The head of the link list.
* @return Return the result.
*/
BOOL isEmpty(PLinkHead _link_head);
/*
To judge whether the node is the last one.
If you get TRUE, then the node is the last one.
* @param stu The node you will judge.
* @param _link_head The head of the link list.
* @return Return the result.
*/
BOOL isLastOne(PLinkNode stu, PLinkHead _link_head);
/*
To get the size of the link list.
* @param _link_head The head of the link