链表的实现方式多种多样,有多个结构体的,有无用头节点的,以下实现方式简化了数据域,没有使用链表结构体,仅有一个结点结构体,思路为用二级指针的方法修改主函数中的头节点来达到修改内存中的链表。
//假装自己是写库函数的,用c语言来实现链表相关函数功能
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define TYPE int
typedef struct Node
{
TYPE data;//数据域
struct Node* next;//指针域
}Node;
//创建结点
Node* create_node(TYPE data)
{
Node* node = malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
//头添加结点
void add_head_list(Node** head,TYPE data)
{
Node* node = create_node(data);
if(NULL != *head)
node->next = *head;
*head = node;
}
//尾添加结点
void add_tail_list(Node** head,TYPE data)
{
Node** tail = head;
while(NULL != *tail)
{
tail = &(*tail)->next;
}
*tail = create_node(data);
}
//删除结点的基本函数
void _del_node(Node** node)
{
Node* temp = *node;
*node = temp->next;
free(temp);
}
//头删除
bool del_head_list(Node** head)
{
if(NULL == *head)
return false;
_del_node(head);
return true;
}
//尾删除
bool del_tail_list(Node** head)
{
if(NULL == *head)
return false;
while(NULL != (*head)->next) head = &(*head)->next;
_del_node(head);
return true;
}
//显示
void show_list(Node* head)
{
while(NULL != head)
{
printf("%d ",head->data);
head = head->next;
}
printf("\n");
}
// 按位置删除
bool del_index_list(Node** head,size_t index)
{
Node** node = head;
while(NULL!=*node && index)
{
// node 要删除的结点的上个结点的指针域地址
node = &(*node)->next;
index--;
}
if(NULL == *node)
return false;
_del_node(node);
return true;
}
//查找功能的基本函数
Noded** query_list(Node** head,TYPE data)
{
Node** node = head;
while(NULL!=*node && data!=(*node)->data)
{
node = &(*node)->next;
}
return node;
}
// 按值删除
bool del_value_list(Node** head,TYPE data)
{
Node** node = query_list(head,data);
if(NULL == *node)
return false;
_del_node(node);
return true;
}
// 删除链表中的重复结点
bool repeat_list(Node** head)
{
Node* node = *head;
while(NULL!=node && NULL!=node->next)
{
if(!del_value_list(&node->next,node->data))
node=node->next;
}
}
//测试功能
int main(int argc,const char* argv[])
{
for(int i=0; i<10; i++)
{
add_tail_list(&head,i);
}
show_list(head);
//del_head_list(&head);
del_tail_list(&head);
//del_index_list(&head,0);
//repeat_list(&head);
show_list(head);
}
版权声明:本文为weixin_54057383原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。