文章目录
- 1.初始化双链表
- 2.创建链表节点
- 3.打印链表
- 4.尾插
- 5.尾删
- 6.头插
- 7.头删
- 8.在pos之前插入
- 8.1 在pos之前插入(改造头插)
- 8.2 在pos之前插入(改造尾插)
- 9.删除pos位置
- 9.1 删除pos位置(改造尾删)
- 9.1 删除pos位置(改造头删)
- 10.查找
- 11.毁灭
链接: 顺序表(动态顺序表增删查改的代码实现) 链接:
单链表(无头单向不循环)增删查改的代码实现
往期顺序表,单链表的代码实现
完整代码见gitee:
链接: 双向链表增删查改的代码实现
1.初始化双链表
LTNode* LTInit()
{
LTNode* phead = CreateLTNode(-1);
phead->next = phead;
phead->prev = phead;
return phead;
}
2.创建链表节点
LTNode* CreateLTNode(LTDataType x)
{
LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
newnode->val = x;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
3.打印链表
void LTPrint(LTNode* phead)
{
assert(phead);
printf("哨兵位<=>");
LTNode* cur = phead->next;
while (cur != phead)
{
printf("%d<=>", cur->val);
cur = cur->next;
}
printf("\n");
}
4.尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
//第一种
assert(phead);
LTNode* tail = phead->prev;
LTNode* newnode = CreateLTNode(x);
//phead tail newnode
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
//第二种
//LTInsert(phead, x);
}
5.尾删
void LTPopBack(LTNode* phead)
{
//第一种
assert(phead);
assert(phead->next != phead);
LTNode* tail = phead->prev;
LTNode* tailPrev = tail->prev;
free(tail);
tailPrev->next = phead;
phead->prev = tailPrev;
//第二种
//LTErase(phead->prev);
}
6.头插
void LTPushFront(LTNode* phead, LTDataType x)
{
//第一种
assert(phead);
LTNode* newnode = CreateLTNode(x);
LTNode* first = phead->next;
phead->next = newnode;
newnode->prev = phead;
newnode->next = first;
first->prev = newnode;
//第二种
//LTInsert(phead->next, x);
}
7.头删
void LTPopFront(LTNode* phead)
{
//第一种
assert(phead);
assert(phead->next != phead);
LTNode* first = phead->next;
LTNode* second = first->next;
phead->next = second;
second->prev = phead;
free(first);
first = NULL;
//第二种
//LTErase(phead->next);
}
8.在pos之前插入
void LTInsert(LTNode* pos, LTDataType x)
{
assert(pos);
LTNode* posPrev = pos->prev;
LTNode* newnode = CreateLTNode(x);
// posprev newnode pos
posPrev->next = newnode;
newnode->prev = posPrev;
newnode->next = pos;
pos->prev = newnode;
}
8.1 在pos之前插入(改造头插)
LTInsert(phead->next, x);
8.2 在pos之前插入(改造尾插)
LTInsert(phead, x);
9.删除pos位置
void LTErase(LTNode* pos)
{
assert(pos);
LTNode* posNext = pos->next;
LTNode* posPrev = pos->prev;
posPrev->next = posNext;
posNext->prev = posPrev;
free(pos);
pos = NULL;
}
9.1 删除pos位置(改造尾删)
LTErase(phead->prev);
9.1 删除pos位置(改造头删)
LTErase(phead->next);
10.查找
LTNode* LTFind(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
if (cur->val == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
11.毁灭
void LTDestroy(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
LTNode* next = cur->next;
free(cur);
cur = next;
}
free(phead);
phead = NULL;
}
完整代码见gitee: 链接:
双向链表增删查改的代码实现