单链表的简单实现

单链表:

链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置)

头文件.结构的定义和 简单函数实现的声明

#pragma once

#include 
#include 
#include 

typedef int DataType;

typedef struct ListNode
{
	DataType data;
	struct ListNode *next;
}ListNode;

ListNode* BuyNode(DataType x);
void PrintList(ListNode *plist);
void PushBack(ListNode **pplist, DataType x);
void PopBack(ListNode **pplist);
void PushFront(ListNode **pplist, DataType x);
void PopFront(ListNode **pplist);
ListNode *Find(ListNode *plist, DataType x);
//在pos前插入一个节点x
void Insert(ListNode **pplist,ListNode *pos, DataType x);
void Erase(ListNode **pplist,ListNode *pos);	//删除pos
函数实现

#include "List.h"

ListNode* BuyNode(DataType x)	//开辟一个新的节点
{
	ListNode *Node = malloc(sizeof(ListNode));
	Node->data = x;
	Node->next = NULL;
	return Node;
}
void PrintList(ListNode *plist)		//打印链表
{
	while(plist)
	{
		printf("%d->",plist->data);
		plist = plist->next;
	}
	printf("NULL\n");

}
void PushBack(ListNode **pplist, DataType x)	//在链表最后压入一个节点
{
	if(NULL == *pplist)
	{
		*pplist = BuyNode(x);
	}
	else if((*pplist)->next == NULL)
	{
		(*pplist)->next = BuyNode(x);
	}
	else
	{
		ListNode *cur = *pplist;
		while(cur->next)
		{
			cur = cur->next;
		}
		cur->next = BuyNode(x);
	}
}
void PopBack(ListNode **pplist)	//弹出链表最后一个节点
{
	if(NULL == *pplist)
		return;
	else if((*pplist)->next == NULL)
	{
		free(*pplist);
		(*pplist) = NULL;
	}
	else
	{
		ListNode *cur = *pplist;
		ListNode *prel = cur;
		while(cur->next)
		{
			prel = cur;
			cur = cur->next;
		}
		free(prel->next);
		prel->next = NULL;
		
	}

}
void PushFront(ListNode **pplist, DataType x)	//链表最前压入一个节点
{
	if(NULL == *pplist)
	{
		(*pplist) = BuyNode(x);
	}
	else
	{
		ListNode* cur = (*pplist);
		(*pplist) = BuyNode(x);
		(*pplist)->next = cur;

	}

}
void PopFront(ListNode **pplist)	//弹出链表第一个节点
{
	if(NULL == *pplist)
		return;
	else if((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		ListNode *cur = (*pplist)->next;
		free(*pplist);
		(*pplist) = cur;
	}

}
ListNode *Find(ListNode *plist, DataType x)	//找到x对应的节点并返回其地址
{
	assert(plist);
	while(plist)
	{
		if(plist->data == x)
			return plist;
		plist = plist->next;
	}
	printf("没找到x\n");
	return NULL;
}
void Insert(ListNode **pplist,ListNode *pos, DataType x)	//在pos前插入一个节点x
{
	assert(pos);
	if(NULL == *pplist)
		return;
	else if((*pplist) == pos)
	{
		PushFront(pplist,x);
	}
	else
	{
		ListNode *cur = *pplist;
		while(cur)
		{
			if(cur->next == pos)
			{
				ListNode* prel = cur->next;
				cur->next = BuyNode(x);
				(cur->next)->next = prel;
				return;
			}
			cur = cur->next;
		}
	}
}
void Erase(ListNode **pplist,ListNode *pos)	//删除pos
{
	assert(pos);
	if(NULL == *pplist)
		return;
	else if(*pplist == pos)
	{
		PopFront(pplist);
	}
	else
	{
		ListNode *cur = *pplist;
		ListNode* prel = cur;
		while(cur->next!=pos)
		{
			cur = cur->next;
		}
		cur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}



你可能感兴趣的:(C语言)