Operations such as adding, deleting, checking and modifying the linked list of the linear list

Operations such as adding, deleting, checking and modifying the linked list of the linear list

#include<stdio.h>
//d定义类型
typedef int LDateType;
//定义结构体类型
typedef struct listNode
{
    
    
	LDateType _date;
	struct listNode* _next;
}listNode;
//定义头指针
typedef struct list
{
    
    
	listNode* _head;
}list;
//初始化头指针
void InistList(list* lst)
{
    
    
	if (lst == NULL)
		return;
	//初始化为空的链表
	lst->_head = NULL;
}
listNode* creatNode(LDateType val)
{
    
    
	listNode* node = (listNode*)malloc(sizeof(listNode));
	node->_date = val;
	node->_next = NULL;
	return node;
}
//尾插
void listPushBack(list* lst, LDateType val)
{
    
    
	if (lst == NULL)
		return;
	//空链表插入
	if (lst->_head==NULL)
	{
    
    
		lst->_head = creatNode(val);
	}
	//非空链表尾插
	else
	{
    
    
		listNode* tail = lst->_head;
		while (tail->_next != NULL)
		{
    
    
			tail = tail->_next;
		}
		tail->_next = creatNode(val);
	}
	
}
//尾删
void listPopBack(list* lst)
{
    
    
	if (lst == NULL||lst->_head==NULL)return;
	struct listNode* tail = lst->_head;
	struct listNode* prev = NULL;
	while (tail->_next != NULL)
	{
    
    
		prev = tail->_next;
		tail = tail->_next;
	}
	//删除节点
	free(tail);
	//修改指向
	if (prev == NULL)//删除的为头结点,更新头结点
		lst->_head = NULL;
	else
	prev->_next = NULL;
}
//头插
void listPushFront(list* lst, LDateType val)
{
    
    
	if (lst == NULL)return;
	//空的链表,插入第一个数据
	if (lst->_head == NULL)
		lst->_head = creatNode(val);
	else
	{
    
    
		listNode* node = creatNode(val);
		listNode* next = lst->_head;
		lst->_head = node;
		node->_next = next;
	}
}
//头删
void listPopFront(list *lst)
{
    
    
	if (lst == NULL || lst->_head == NULL)return; 
	listNode* next = lst->_head->_next;
	//释放头结点
	free(lst->_head);
	lst->_head = next;
}
//第一个元素后后插入
void listInsertAfter(listNode* cur, LDateType val)
{
    
    
	listNode* node = creatNode(val);
	listNode* next = cur->_next;
	cur->_next = node;
	node->_next = next;
}
//删除第二个元素
void listEraseAfter(listNode* cur)
{
    
    
	listNode* next = cur->_next;
	if (next == NULL)return;
	listNode* nextnext = next->_next;
	free(next);
	cur->_next=nextnext;
}
//查找值为val,返回地址
listNode* listFind(list* lst,LDateType val)
{
    
    
	if (lst == NULL || lst->_head == NULL)return;
	//从第一个值开始遍历
	listNode* cur = lst->_head;
	while (cur)
	{
    
    
		if (cur->_date == val)
			return cur;
		cur = cur->_next;
	}
	return NULL;
}
//求链表的大小
int listSize(list* lst)
{
    
    
	if (lst == NULL)return;
	int count = 0;
	listNode* next = lst->_head;
	while (next)
	{
    
    
		next = next->_next;
		count++;
	}
	return count;
}
//销毁链表
void listDestroy(list* lst)
{
    
    
	if (lst == NULL||lst->_head==NULL)return;
	listNode*  ps = lst->_head,*next = NULL;
	while (ps)
	{
    
    
		next = ps->_next;
		free(ps);
		ps = next;
	}
	lst->_head = NULL;

}

Guess you like

Origin blog.csdn.net/weixin_52270223/article/details/111084108