数据结构:单链表(不带头结点)
程序员文章站
2024-03-21 14:48:58
...
nlist.h
#pragma once
typedef struct NNode
{
int data;
struct NNode *next;
}NNode,*NList;
//链表初始化
void InitList(NList *pplist);
//头插
bool Insert_head(NList *pplist,int val);
//尾插
bool Insert_tail(NList *pplist,int val);
//查找
NNode *Search(NList plist,int key);
//删除
bool Delete(NList *pplist,int key);
//获取长度
int GetLength(NList plist);
//判空
bool IsEmpty(NList plist);
//清空
void Clear(NList *pplist);
//摧毁
void Destroy(NList *pplist);
//打印
void Show(NList plist);
nlist.cpp
#pragma once
//不带头结点的单链表
typedef struct NNode
{
int data;
struct NNode *next;
}NNode,*NList;
//链表初始化
void InitList(NList *pplist)
{
assert(pplist != NULL);
*pplist = NULL;
}
//头插
bool Insert_head(NList *pplist,int val)
{
NNode* p =(NNode*)malloc(sizeof(NNode));
p->data = val;
p->next = *pplist;
*pplist = p;
return true;
}
//尾插
bool Insert_tail(NList *pplist,int val)
{
NNode* p =(NNode*)malloc(sizeof(NNode));
p->data = val;
p->next = NULL;
if(*pplist == NULL)
{
*pplist = p;
return true;
}
NNode *q;
for(q = *pplist;q->next != NULL;q = q->next);//找尾巴
q->next = p;
return true;
}
//查找
NNode *Search(NList plist,int key)
{
Node*p;
for(p = plist->next; p != NULL ;p = p->next)
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
//删除
bool Delete(NList *pplist,int key)
{
if(*pplist == NULL)
{
return false;
}
NNode*p = *pplist;
//删除第一个点
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;
}
//获取长度
int GetLength(NList plist)
{
int count = 0;
for(NNode*p = plist->next; p != NULL ;p = p->next)
{
count++;
}
return count;
}
//判空
bool IsEmpty(NList plist)
{
return plist == NULL;
}
//清空
void Clear(NList *pplist)
{
Destroy(pplist);
}
//摧毁
void Destroy(NList *pplist)
{
NNode *p;
while(*pplist != NULL)
{
p = *pplist;
*pplist = p->next ;
free(p);
}
*pplist == NULL;
}
//打印
void Show(NList plist)
{
NNode *p;
for(p = plist->next; p != NULL ; p = p->next)
{
printf("%d",p->data);
}
printf("\n");
}
主函数
#include<stdio.h>
#include<stdlib.h>
#include<vld.h>
#include"nlist.h"
int main()
{
NList list;
InitList(&list);
for(int i=0;i<15;i++)
{
//Insert_head(&list,i);
Insert_tail(&list,i);
}
//查找测试用例
/*NNode *s1 = Search(list,3);
NNode *s2 = Search(list,-1);
NNode *s3 = Search(list,15);
printf("%d\n",s1->data);
printf("%d\n",s2->data);
printf("%d\n",s3->data);*/
//删除测试用例
/*Delete(&list,-1);
Delete(&list,18);
Delete(&list,0);
Delete(&list,5);
Delete(&list,14);
Show(list);*/
//获取长度测试
printf("%d\n",GetLength(list));
Show(list);
Destroy(&list);
Destroy(&list);
return 0;
}
上一篇: grails 初体验
下一篇: 数据结构——单链表(不带头结点)