赞
踩
在工作中的项目有用到双链表,尤其是跟着别人写双链表代码的思路,自己去看总觉得没那么顺,感觉以后也会经常用到,所以索性自己写一个出来,细节由自己去把握,终于是理解了这一块,以下是实现双链表的所有源码:
#include <stdio.h> #include <malloc.h> typedef struct List { struct List *pre; struct List *next; int data; }List_t; typedef struct HeadNode { int nodeLenth; //用于存储节点的长度 List_t *headNode; //头结点 }HeadNode_t; //初始化头结点 HeadNode_t g_headNode = { .nodeLenth = 0, .headNode = NULL, }; //双向循环链表 //插入结点 void InsertNode(List_t *ListMember) { unsigned char i = 0; if(g_headNode.nodeLenth == 0) { //插入的第一个结点当做头结点 g_headNode.nodeLenth++; g_headNode.headNode = ListMember; g_headNode.headNode->next = ListMember; //第一个结点的next指向自己,主要是为了构成双向循环链表 g_headNode.headNode->pre = ListMember; //第一个结点的pre指向自己 return; } g_headNode.nodeLenth++; List_t *tempNode = g_headNode.headNode->pre; //tempNode永远表示链表的最后一个节点 tempNode->next = ListMember; //插入的结点放到最后 g_headNode.headNode->pre = ListMember; ListMember->next = g_headNode.headNode; ListMember->pre = tempNode; tempNode = g_headNode.headNode; //打印结点 for(i = 1; i <= g_headNode.nodeLenth; i++) { printf("The data%d is %d\n", i, tempNode->data); tempNode = tempNode->next; } } //根据数据找到结点 List_t* FindDataNode(int data) { unsigned char i; List_t *tempNode = g_headNode.headNode; for(i = 0; i < g_headNode.nodeLenth; i++) { if(tempNode->data == data) { return tempNode; } tempNode = tempNode->next; } return NULL; } //删除结点 void DelDataNode(int data) { unsigned char i = 0; List_t *DelNode = FindDataNode(data); g_headNode.nodeLenth--; if(DelNode == g_headNode.headNode) { //如果删除的是头结点 g_headNode.headNode->pre->next = DelNode->next; g_headNode.headNode->next->pre = DelNode->pre; g_headNode.headNode = DelNode->next; for(i = 1; i <= g_headNode.nodeLenth; i++) { printf("After del HeadNode, the data%d is %d\n", i, DelNode->next->data); DelNode = DelNode->next; } return; } DelNode->next->pre = DelNode->pre; //删除结点的具体操作 DelNode->pre->next = DelNode->next; DelNode = g_headNode.headNode; for(i = 1; i <= g_headNode.nodeLenth; i++) { printf("The data%d is %d\n", i, DelNode->data); DelNode = DelNode->next; } } //设置结点为头结点 void SetHeadNode(int data) { List_t *TempNode = FindDataNode(data); g_headNode.headNode = TempNode; } int main(void) { List_t *listMember1 = NULL; listMember1 = (List_t *)malloc(sizeof(List_t)); listMember1->data = 18; listMember1->next = NULL; listMember1->pre = NULL; List_t *listMember2 = NULL; listMember2 = (List_t *)malloc(sizeof(List_t)); listMember2->data = 19; listMember2->next = NULL; listMember2->pre = NULL; InsertNode(listMember1); InsertNode(listMember2); DelDataNode(18); printf("The lenth is %d\n", g_headNode.nodeLenth); free(listMember1); free(listMember2); return 0; }
若是大家有其他想法或者有发现错误,欢迎指正哈~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。