数据结构之单向链表(C语言实现)
Posted 乌云中的闪电
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构之单向链表(C语言实现)相关的知识,希望对你有一定的参考价值。
1.创建结构体
struct Node
{
int data;
struct Node* next;
};
2.创建新的节点
struct Node* Creatlist()
{
struct Node* HeadNode = (struct Node*)malloc(sizeof(struct Node));
HeadNode->next = NULL;
return HeadNode;
}
3.三种插入法
(1)头插法
void insert_By_Head(struct Node* Headnode, int data)
{
struct Node* newNode = CreateNode(data);
newNode->next = Headnode->next;
Headnode->next = newNode;
}
(2)尾插法
void insert_By_Tail(struct Node* HeadNode, int data)
{
struct Node* NewNode = CreateNode(data);
struct Node* TailNode = HeadNode;
while (TailNode->next != NULL)
TailNode = TailNode->next;
NewNode->next = TailNode->next;
TailNode->next = NewNode;
}
(3)指定插入法
void insert_By_appoint_pos(struct Node* HeadNode, int data, int posdata)
{
struct Node* posFrontNode = HeadNode;
struct Node* posNode = HeadNode->next;
while (posNode != NULL && posNode->data != posdata)
{
posFrontNode = posNode;
posNode = posFrontNode->next;
}
if (posNode == NULL)
printf("未找到指定位置,无法插入!\\n");
else
{
struct Node* newNode = CreateNode(data);
posFrontNode->next = newNode;
newNode->next = posNode;
}
}
4.三种删除法
(1)头删法
void delete_By_Head(struct Node* HeadNode)
{
struct Node* nextNode = HeadNode->next;
if (nextNode == NULL)
{
printf("链表为 NULL,无法删除!\\n");
return;
}
HeadNode->next = nextNode->next;
free(nextNode);
}
(2)尾删法
void delete_By_Tail(struct Node* HeadNode)
{
struct Node* TailFrontNode = HeadNode;
struct Node* TailNode = HeadNode->next;
if (TailNode == NULL)
{
printf("链表为 NULL,无法删除!\\n");
return;
}
while (TailNode->next != NULL)
{
TailFrontNode = TailNode;
TailNode = TailFrontNode->next;
}
TailFrontNode->next = NULL;
free(TailNode);
}
(3)指定位置删除法
void delete_By_Appoint_pos(struct Node* HeadNode, int posdata)
{
struct Node* posFrontNode = HeadNode;
struct Node* posNode = HeadNode->next;
while (posNode != NULL && posNode->data != posdata)
{
posFrontNode = posNode;
posNode = posFrontNode->next;
}
if (posNode == NULL)
{
printf("未找到指定节点,无法删除!\\n");
return;
}
else
{
posFrontNode->next = posNode->next;
free(posNode);
}
}
5.打印链表
void PrintList(struct Node* HeadNode)
{
struct Node* pMove = HeadNode->next;
while (pMove)
{
printf("%d-->", pMove->data);
pMove = pMove->next;
}
printf("\\n");
}
以上是关于数据结构之单向链表(C语言实现)的主要内容,如果未能解决你的问题,请参考以下文章