单链表:单链表是一种连式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象)+指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每一个结点的地址数据。
typedef struct Node
{
int data;
struct Node *next;
}Node,*List;
void InitList(List plist);//初始化单链表
bool Insert_head(List plist,int val);//头插法
bool Insert_tail(List plist,int val);//尾插法
bool Insert_pos(List plist,int pos,int val);//pos 位置插入
Node *Search_pre(List plist,int key);//查找 key 的前驱
bool Delete(List plist,int key);//删除 key 这个结点
bool IsEmpty(List plist);//是否为空
void Destroy(List plist);//摧毁函数(如果有动态开辟内存)
int GetLength(List plist);//得到单链表的长度
void Show(List plist);//打印单链表
代码:
void InitList(List plist)
{
assert(plist != NULL);
if(plist == NULL)
{
return;
}
plist->next = NULL;
static Node*GetNode(int val)
{
Node *p = (Node*)malloc(sizeof(Node));
assert( p != NULL);
p->data = val;
p->next = NULL;
return p;
}
bool Insert_head(List plist,int val)
{
assert(plist != NULL);
Node *p = GetNode(val);
p->next = plist->next;
plist->next = p;
return true;
}
bool Insert_tail(List plist,int val)
{
assert(plist != NULL);
Node *p = plist;
while(p->next != NULL)
{
p = p->next;
}
Node *pGet = GetNode(val);
p->next = pGet;
return true;
}
bool Insert_pos(List plist,int pos,int val)
{
assert(plist != NULL);
Node *p = plist;
if(pos < 0 || pos > GetLength(plist))
{
return false;
}
for(int i = 0;i <= pos - 1;i++)
{
p = p->next;
}
Node *pGet = GetNode(val);
pGet->next = p->next;
p->next = pGet;
return true;
}
Node *Search_pre(List plist,int key)//查找key 的前驱
{
assert(plist != NULL);
Node *p;
for(p = plist;p->next != NULL;p = p->next)
{
if(p->next->data == key)
{
return p;
}
}
return NULL;
}
bool Delete(List plist,int key)
{
assert(plist != NULL);
Node *p = Search_pre(plist,key);
assert(p != NULL);
Node *q = p->next;
p->next = q->next;
free(q);
q = NULL;
return true;
}
bool isEmpty(List plist)
{
if(plist->next == NULL)
{
return true;
}
return false;
}
void Destroy(List plist)
{
assert(plist != NULL);
Node *p;
for(p = plist->next;p->next != NULL;p = p->next)
{
free(p);
p = NULL;
}
}
int GetLength(List plist)
{
assert(plist != NULL);
int count = 0;
for(Node *p = plist;p->next != NULL;p = p->next)
{
count++;
}
return count;
}
void Show(List plist)
{
assert(plist != NULL);
Node *p;
for(p = plist->next;p != NULL;p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
测试:
#include<stdio.h>
#include"List.h"
int main()
{
Node head;
InitList(&head);
for(int i = 0;i <= 9;i++)
{
Insert_tail(&head,i);
}
Show(&head);
Insert_tail(&head,34);
Show(&head);
Insert_pos(&head,3,24);
Show(&head);
Node *tmp = Search_pre(&head,8);
printf("%d\n ",tmp->data);
Delete(&head,5);
Show(&head);
int len = GetLength(&head);
printf("%d ",len);
return 0;
}