LinkList.h头文件
typedef struct Node
{
int data;
Node* next;
}Node;
typedef Node* LinkList;
//初始化函数
void InitList(LinkList plist);
//头插
bool Insert_head(LinkList plist, int val);
//尾插
bool Insert_tail(LinkList plist, int val);
//在plist中查找关键字key,找到返回下标,失败返回NULL
Node* Search(LinkList plist, int key);
//判空
bool IsEmpty(LinkList plist);
//删除plist中的第一个key
bool DeleteVal(LinkList plist, int key);
//获取数据长度
int GetLength(LinkList plist);
//输出所有数据
void Show(LinkList plist);
//销毁动态内存
void Destroy(LinkList plist);
//单链表逆置
void Reverse(LinkList plist);
函数的具体实现:
LinkList.cpp文件
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "LinkList.h"
**函数的具体实现:**
/*初始化函数*/
void InitList(LinkList plist)
{
assert(plist != NULL);
if (plist == NULL)
return;
plist->next = NULL;
}
/*头插*/
bool Insert_head(LinkList plist, int val)
{
assert(plist != NULL);
if (plist == NULL)
{
return false;
}
//申请一个新节点
Node* p = (Node*)malloc(sizeof(Node));
p->data = val;
//将新节点插入链表
p->next = plist->next;
plist->next = p;
return true;
}
/*尾插*/
bool Insert_tail(LinkList plist, int val)
{
assert(plist != NULL);
if (plist == NULL)
return false;
//申请新节点
Node* p = (Node*)malloc(sizeof(Node));
p->data = val;
//找尾节点
while (plist->next != NULL)
{
plist = plist->next;
}
//将新节点插入链表
p->next = plist->next;
plist->next = p;
return true;
}
/*在plist中查找关键字key,找到返回指针,失败返回NULL*/
Node* Search(LinkList plist, int key)
{
assert(plist != NULL);
Node* p = plist->next;
while (p != NULL)
{
if (p->data == key)
{
return p;
}
p = p->next;
}
return NULL;
}
/*判空*/
bool IsEmpty(LinkList plist)
{
return plist->next == NULL;
}
/*查找前驱节点,找到返回指针,失败返回NULL*/
static Node* SearchPrio(LinkList plist, int key)
{
for (Node* p = plist; p->next != NULL; p = p->next)
{
if (p->next->data == key)
{
return p;
}
}
return NULL;
}
/*删除plist中的第一个key*/
bool DeleteVal(LinkList plist, int key)
{
assert(plist != NULL);
//找到前驱节点
Node *p= SearchPrio(plist, key);
if (p == NULL)
{
return false;
}
//将p从链表中剔除
Node* q = p->next;//q指向要删除的节点
p->next = q->next;
free(q);
q = NULL;
return true;
}
/*获取数据长度*/
int GetLength(LinkList plist)
{
assert(plist != NULL);
int count = 0;
Node* p = plist->next;
while (p != NULL)
{
p = p->next;
count++;
}
return count;
}
/*输出所有数据*/
void Show(LinkList plist)
{
assert(plist != NULL);
Node *p = plist->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/*销毁动态内存*/
void Destroy(LinkList plist)
{
assert(plist != NULL);
Node* p;
//总是删除第一个结点
while (plist->next != NULL)
{
p = plist->next;
plist->next = p->next;
free(p);
}
plist->next = NULL;
}
/*单链表逆置*/
void Reverse(LinkList plist)
{
assert(plist != NULL);
Node* p = plist->next;
Node* q;
plist->next = NULL;//与原链表断开
while (p != NULL)
{
q = p;
p = p->next;
//新链
q->next = plist->next;
plist->next = q;
}
}