只实现了初始化、头插、尾插、按值删、判空、输出的功能
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;
}