天天看点

数据结构:单链表基础操作

函数实现:

1.初始化

2.尾插

3.头插

4.按关键字删除

5.查找

自定义头文件:

typedef int ELEM_TYPE;

typedef struct Node
{
	ELEM_TYPE mdata;
	struct Node* pnext;
}Node, *Link;


void Init(Link phead);
static Link BuyNode();
bool InsertTail(Link phead, ELEM_TYPE val);
bool InsertHead(Link phead, ELEM_TYPE val);

bool DeleteKey(Link phead, ELEM_TYPE val);

Node* Search(Link phead, ELEM_TYPE val);

void Print(Link phead);

void Clear(Link phead);
void Destory(Link phead);
           

 函数实现:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

#include "Link.h"
void Init(Link phead)
{
	assert(phead != NULL);
	if (phead == NULL)
	{
		return;
	}
	phead->pnext = NULL;
}

//void* malloc(size_t size);
static Link BuyNode()
{
	struct Node* pnewnode = (struct Node*)malloc(sizeof(struct Node));
	assert(pnewnode != NULL);
	pnewnode->pnext = NULL;
	return pnewnode;
}
bool InsertTail(Link phead, ELEM_TYPE val)
{
	if (phead == NULL)
	{
		return false;
	}
	struct Node* pCur = phead;
	while (pCur->pnext != NULL)
	{
		pCur = pCur->pnext;
	}
	struct Node* pnewnode = BuyNode();
	pnewnode->mdata = val;

	pCur->pnext = pnewnode;
	return true;
}
bool InsertHead(Link phead, ELEM_TYPE val)
{
	if (phead == NULL)
	{
		return false;
	}
	struct Node* pnewnode = BuyNode();
	pnewnode->mdata = val;

	pnewnode->pnext = phead->pnext;
	phead->pnext = pnewnode;
	return true;
}

bool DeleteKey(Link phead, ELEM_TYPE val);

Node* Search(Link phead, ELEM_TYPE val);

void Print(Link phead)
{
	if (phead == NULL)
	{
		return;
	}
	struct Node* pCur = phead->pnext;
	while (pCur != NULL)
	{
		printf("%d ", pCur->mdata);
		pCur = pCur->pnext;
	}
	printf("\n");
}

void Clear(Link phead)//清理数据结点
{
	struct Node* pCur = phead->pnext; //pCur 当前要删除的结点
	struct Node* pNext = pCur;
	while (pCur != NULL)
	{
		pNext = pCur->pnext;
		free(pCur);
		pCur = pNext;
	}
	phead->pnext = NULL;
}
void Destory(Link phead)
{
	Clear(phead);
	//free(phead);
}
           

继续阅读