链表
前言
基础知识
Code Block
struct Node
{
int data;
struct Node* next;
};
创建链表(用表头表示整个链表)
//创建链表表头(结点)
struct Node* CreatList()
{
struct Node* HeadNode = (struct Node*)malloc(sizeof(struct Node));
HeadNode->next = NULL;
return HeadNode;
};
创建结点(增加链表结点)
struct Node* NewNode(int data)
{
struct Node* NewNode = (struct Node*)malloc(sizeof(struct Node));
NewNode->data = data;
NewNode->next = NULL;
return NewNode;
};
遍历整个链表,打印链表
void PrinfList(struct Node* HeadNode)
{
struct Node* pMove = HeadNode->next;
while (pMove)
{
printf("%d\n", pMove->data);
pMove = pMove->next;
}
}
查找指定数据
//查找指定数据
struct Node* ListFind(struct Node* Head, int data)
{
struct Node* cur = Head;
while (cur != NULL)
{
if(cur->data == data)
{
return cur;
}
else
{
cur = cur->next;
}
}
return NULL;
}
插入结点
头插
//头插
void ListPushFront(struct Node* Head, int data)
{
struct Node* insertNode = NewNode(data);
insertNode->next = Head->next;
Head->next = insertNode;
}
尾插
//尾插
void ListPushBack(struct Node* Head, int data)
{
struct Node* insertNode = NewNode(data);
if(Head == NULL)
{
Head->next = insertNode;
}
else
{
struct Node* pMove = Head->next;
while(pMove->next != NULL)
{
pMove = pMove->next;
}
pMove->next = insertNode;
}
}
删除结点
尾删
void ListPopFront(struct Node* HeadNode)
{
struct Node* pMove = HeadNode->next;
struct Node* temp = NULL;
if(Head == NULL)
{
return;
}
else
{
while(pMove->next != NULL)
{
temp = pMove;
pMove = pMove->next;
}
free(pMove);
pMove = NULL;
temp->next = NULL;
}
}
删除指定数据
//删除结点
void deletNode(struct Node* HeadNode, int data)
{
struct Node* pMove = HeadNode->next;
if (pMove == NULL)
{
HeadNode->next == NULL;
}
//遍历链表,找到链表中第一个结点的值和要被删除的结点值比较
else
{
while ((data != pMove->data)&&(pMove->next != NULL))
{
pMove = pMove->next;
HeadNode = HeadNode->next;
}
if (data == pMove->data)
{
HeadNode->next = pMove->next;
free(pMove);
pMove = NULL;
}
}
}
删除指定结点
//删除结点
void delete(struct Node* HeadNode, struct Node* node)
{
struct Node* pMove = HeadNod->next;
if(node == HeadNode)
{
ListPopFront(HeadNode);
}
else
{
while(pMove->next != node)
{
pMove = pMove->next;
}
pMove->next = node->next;
free(node);
node = NULL;
}
}