- 链表的的特点是用一组任意的储存单元储存线性表的数据元素(储存单元不一定连续)
- 链表的表示形式
为了表示每个数据元素与后继元素之间的逻辑关系,除了储存其本身的信息外,使用一个变量存储其直接后继的信息
链表由一个个结点组成,每个结点包含数据域和指针域
单链表的实现----带头结点
List.h
#pragma once
//带头节点的单链表
//单链表的尾节点next为NULL
typedef struct Node
{
int data;
struct Node *next;
}Node,*List;//List == Node *
//typedef Node *List;
//初始化
void InitList(List plist);
//头插法
bool Insert_head(List plist,int val);
//尾插
bool Insert_tail(List plist,int val);
//查找
Node *Search(List plist,int key);
//删除
bool Delete(List plist,int key);
bool IsEmpty(List plist);
//获取长度,数据个数
int GetLength(List plist);
void Show(List plist);
//获得key的前驱
Node *GetPrio(List plist,int key);
//获取key后继
Node *GetNext(List plist,int key);
//清空数据
void Clear(List plist);
//销毁
void Destroy(List plist);
List.cpp
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "list.h"
//初始化
void InitList(List plist)
{
assert(plist != NULL);
if(plist == NULL)
{
return ;
}
plist->next = NULL;
}
//头插法,新的数据插入在头节点的后面
bool Insert_head(List plist,int val) //先绑绳子,再剪
{
//Node newnode; //1 error 局部变量,生命周期
//newnode.data = val;//2
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
p->next = plist->next;//4
plist->next = p;//3
return true;
}
//尾插
bool Insert_tail(List plist,int val)
{
Node *p;
for(p=plist;p->next!=NULL;p=p->next) ;//p走到最后一个节点
Node *q = (Node *)malloc(sizeof(Node));
q->data = val;
//将q插入在p的后面
q->next = p->next;//q->next = NULL;
p->next = q;
return true;
}
//查找
Node *Search(List plist,int key)
{
for(Node *p=plist->next;p!=NULL;p=p->next)
{
if(p->data == key)
{
return p;
}
}
return NULL;
}
//删除
bool Delete(List plist,int key)
{
Node *p = GetPrio(plist,key);
if(p == NULL)
{
return false;
}
Node *q = p->next;
p->next = p->next->next;//p->next = q->next;
free(q);
return true;
}
bool IsEmpty(List plist)
{
return plist->next == NULL;
}
//获取长度,数据个数
int GetLength(List plist)
{
int count = 0;
for(Node *p=plist->next;p!=NULL;p=p->next)
{
count++;
}
return count;
}
//遍历所有的数据节点
void Show(List plist)
{
assert(plist != NULL);
for(Node *p=plist->next;p!=NULL;p=p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
//获得key的前驱
Node *GetPrio(List plist,int key)
{
assert(plist!=NULL);
for(Node *p=plist;p->next!=NULL;p=p->next)
{
if(p->next->data == key)
{
return p;
}
}
return NULL;
}
//获取key后继
Node *GetNext(List plist,int key)
{
Node *p = Search(plist,key);
if(p == NULL)
{
return NULL;
}
return p->next;
}
//清空数据
void Clear(List plist)
{
Destroy(plist);
}
//销毁
void Destroy(List plist)
{
Node *p;
while(plist->next != NULL)
{
p = plist->next;
plist->next = p->next;
free(p);
}
/*
Node *p = plist->next;
Node *q;
plist->next = NULL;
while(p != NULL)
{
q = p->next;
free(p);
p = q;
}
*/
}