数据结构(C语言)无头结点的单链表

只实现了初始化、头插、尾插、按值删、判空、输出的功能

nolist.h文件

#pragma once

typedef struct NNode
{
	int data;
	struct NNode* next;
}NNode,*NList;

void InitList(NList* pplist);//和之前不一样,pplist是二级指针

static NNode* BuyNode(int val);

bool Insert_Head(NList* pplist, int val);

bool Insert_Tail(NList* pplist, int val);

bool DelKey(NList* pplist, int key);

NNode* Search(NList plist, int key);//动了头是二级指针,不动是一级指针

int GetLength(NList plist);

bool IsEmpth(NList plist);

void Show(NList plist);

void Destory(NList* pplist);

nolist.cpp文件

#include"nolist.h"
#include<stdio.h>
#include<assert.h>
#include<malloc.h>

void InitList(NList* pplist)//和之前不一样,pplist是二级指针
{
	assert(pplist != NULL);
	if (pplist == NULL)
	{
		return;
	}
	*pplist = NULL;
}

static NNode* BuyNode(int val)
{
	NNode* p = (NNode*)malloc(sizeof(NNode));
	assert(p != NULL);
	p->data = val;
	p->next = NULL;
	return p;
}


bool Insert_Head(NList* pplist, int val)
{
	assert(pplist != NULL);//二级指针要断言
	if (pplist == NULL)
	{
		return false;
	}
	NNode* p = BuyNode(val);
 
	p->next = *pplist;
	*pplist = p;

	return true;
}

bool Insert_Tail(NList* pplist, int val)
{
	assert(pplist != NULL);//二级指针要断言
	if (pplist == NULL)
	{
		return false;
	}

	NNode* p = BuyNode(val);
	NNode* q = *pplist;
	if (q == NULL)//插第一个时会崩溃
	{
		*pplist = p;
	}
	else
	{
		for (q = *pplist; q->next != NULL; q = q->next)
		{
			;
		}
		q->next = p;
	}
	return true;
}

bool DelKey(NList* pplist, int key)
{
	assert(pplist != NULL);
	if (pplist == NULL)
	{
		return false;
	}
	NNode* p = *pplist;
	if (p == NULL)//*pplist==NULL
		return false;
	if (p->data == key)
	{
		*pplist = p->next;
		free(p);
		return true;
	}
	for (p = *pplist; p->next!=NULL; p = p->next)
	{	
		if (p->next->data == key)
		{
			NNode* q = p->next;
			p->next = q->next;
			free(q);
			return true;
		}
		
	}
	return false;
}

NNode* Search(NList plist, int key);//动了头是二级指针,不动是一级指针

int GetLength(NList plist);

bool IsEmpth(NList plist)
{
	return plist == NULL;
}

void Show(NList plist)
{
	/*assert(plist != NULL);//不用写,传的一级指针,plist为空
	if (plist == NULL)
	{
		return;
	}*/
	for (NNode* p = plist; p != NULL; p = p->next)//注意:NNode* p = plist; p != NULL; p = p->next
	{
		printf("%d  ", p->data);
	}
	printf("\n");
}

void Destory(NList* pplist);

main.cpp文件//测试

#include"nolist.h"
int main()
{
	NList plist;
	InitList(&plist);
	for (int i = 0; i < 10; i++)
	{
		//Insert_Head(&plist, i);
		Insert_Tail(&plist, i);
	}
	//Insert_Tail(&plist, 0);
	Show(plist);
	DelKey(&plist, 0);
	Show(plist);
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值