单链表是数据结构中比较基础的知识
主要涉及到的函数有:
- 单链表的初始化
- 数据头插法
- 据尾插法
- 按pos位置插入
- 查找key值前驱
- 删除key值结点
- 得到单链表的长度
- 摧毁单链表
/* 头文件 */
typedef int Elemtype;
typedef struct LNode
{
Elemtype date;
struct LNode *next;
}LNode,*Linklist;
void Initlist(Linklist L );//初始化单链表
bool Insert_head(Linklist L,Elemtype val);//头插法
bool Insert_tail(Linklist L,Elemtype val);//尾插法
bool Insert_pos(Linklist L,int pos, Elemtype val);//pos位置插入
LNode*Search(Linklist L,int key);//查找key的前驱
bool Delete(Linklist L,int key);//删除key结点
bool Is_empty(Linklist L);//是否为空
bool Destroy(Linklist L);//摧毁函数
int Getlength(Linklist L);//得到单链表的长度
void Show(Linklist L);//打印单链表
/* 函数的实现 list.cpp */
#include<stdio.h>
#include<stdlib.h>
#include"Linklist.h"
#include<assert.h>
void Initlist(Linklist L)//初始化单链表
{
assert(L!=NULL);
L->next=NULL;
}
static LNode*GetNode(Elemtype val)//创建一个新结点
{
LNode *pGet=(LNode*)malloc(10*sizeof(LNode));
assert(pGet!=NULL);
pGet->date=val;
pGet->next=NULL;
return pGet;
}
bool Insert_head(Linklist L,Elemtype val)//头插法
{
assert(L!=NULL);
LNode *pGet=GetNode(val);
pGet->next=L->next;
L->next=pGet;
return true;
}
bool Insert_tail(Linklist L,Elemtype val)//尾插法
{
assert(L!=NULL);
LNode *pGet=GetNode(val);
LNode *p=L->next;
while(p->next!=NULL)
{
p=p->next;
}
p->next=pGet;
return true;
}
int Getlength(Linklist L)//得到单链表的长度
{
int i=0;
LNode *p=L->next;
while(p!=NULL)
{
p=p->next;
i++;
}
return i;
}
bool Insert_pos(Linklist L,int pos, Elemtype val)//pos位置插入
{
assert(L!=NULL);
if(pos<0||pos>Getlength(L))
{
return false;
}
LNode *pGet=GetNode(val);
LNode *p=L;
int i=0;
while(i!=pos)
{
p=p->next;
}
pGet->next=p->next;
p->next=pGet;
}
LNode*Search(Linklist L,int key)//查找key的前驱
{
assert(L!=NULL);
if(Is_empty(L))
{
return NULL;
}
LNode *p=L;
for(;p->next!=NULL;p=p->next)
{
if(p->next->date==key)
return p;
}
return NULL;
}
bool Delete(Linklist L,int key)//删除key结点
{
assert(L!=NULL);
if(Is_empty(L))
{
return false;
}
LNode *p=L;
while(p->next!=NULL)
{
if(Search( L, key)!=NULL)
{
LNode *q=Search( L, key);
p=q->next;
q->next=p->next;
p=q;
}
else
{
p=p->next;
}
}
return true;
}
bool Is_empty(Linklist L)//是否为空
{
if(L->next==NULL)
return true;
return false;
}
bool Destroy(Linklist L)//摧毁函数
{
assert(L!=NULL);
LNode *p=NULL;
while(L->next!=NULL)
{
p=L->next;
L->next=p->next;
free(p);
}
p=NULL;
printf("链表已摧毁。\n");
return true;
}
void Show(Linklist L)//打印单链表
{
assert(L!=NULL);
LNode *p=L->next;
while(p!=NULL)
{
printf("%d ",p->date);
p=p->next;
}
printf("\n");
}
/* 主函数 */
#include<stdio.h>
#include<stdlib.h>
#include"Linklist.h"
int main()
{
LNode head;
Initlist(&head);
//头插
for(int i=0;i<5;i++)
{
Insert_head(&head,i);
//Insert_tail(&head,i);
}
Show(&head);
//尾插
for(int j=0;j<5;j++)
{
Insert_tail(&head,j);
}
Show(&head);
//打印链表长度
printf("%d\n",Getlength(&head));
//位置插入
Insert_pos(&head,0, 11);
Show(&head);
//key值前驱的数据
printf("%d\n",Search(&head,0)->date);
//删除某一元素
Delete(&head,4);
Show(&head);
//摧毁函数
Destroy(&head);
system("pause");
return 0;
}