一. 基本概念
(1)链表的n个节点离散;彼此通过指针相连;每个节点只有一个前驱节点,每个节点只有一个后续节点;首节点没有前驱节点,为节点没有后续节点。
(2)几个概念:
● 首节点:第一个有效节点
● 尾节点:最后一个有效节点
● 头节点:首节点之前附设的一个节点,不存放有效数据
● 头指针:指向头节点的指针变量
● 尾指针:指向尾节点的指针变量
(3)通过一个函数对单链表进行操作,必须的一个参数是 头指针(因为可以通过头指针推选出其他信息)
(4)链表的每一个节点都由两部分构成:数据域和指针域,其中指针的类型和节点的类型一致。
(5)分类:
单链表,双链表,循环链表,非循环链表
(6)操作:
遍历,查找,插入,删除,清空,销毁,求长度和排序等
二. 链表操作
(1) 创建链表
void CreatList( pNode head, int *a )
{
if ( head == NULL || a == NULL)
{
return;
}
pNode tail = head; //从前往后添加时使用
for ( int i=0; i<n; i++ )
{
pNode nodeNew = (pNode)malloc(sizeof(NODE));
if (nodeNew == NULL)
{
printf("分配失败");
return;
}
//从后往前添加
//nodeNew->next = head->next;
//nodeNew->data = a[i];
//head->next = nodeNew;
//从前往后添加
tail->next = nodeNew;
nodeNew->data = a[i];
nodeNew->next = NULL;
tail = nodeNew;
}
}
(2) 插入
void InsetList( pNode head, int pos, int num)
{
if ( pos < 1 || pos > n+1 || head == NULL )
{
return ;
}
//寻找第pos个节点
int i=1;
pNode p = head->next;
while ( i< pos-1 && p != NULL )
{
p = p->next;
i++;
}
//插入的节点
pNode newNode = (pNode)malloc(sizeof(NODE));
if ( newNode == NULL )
{
return ;
}
newNode->data = num;
newNode->next = p->next;
p->next = newNode;
}
(3) 删除
void DeleteList( pNode head, int pos)
{
if ( head == NULL || pos <1 || pos > n)
{
return ;
}
int i=1;
pNode p = head->next;
while ( i< pos-1 && p != NULL )
{
p = p->next;
i++;
}
//删除的节点
pNode deleteNode;
deleteNode = p->next;
p->next = p->next->next;
free( deleteNode );
}
(4) 排序(冒泡)
void SortList( pNode head )
{
if ( head == NULL )
{
return ;
}
for ( int i=0; i<n-1; i++ )
{
pNode p = head->next;
int t;
for ( int j=0; j<n-i-1 ; j++, p=p->next )
{
if ( p->data > p->next->data )
{
t = p->next->data;
p->next->data = p->data;
p->data = t;
}
}
}
}
(5) 遍历输出
void PrintList( pNode head )
{
if ( head == NULL )
{
return;
}
pNode p = head->next;
do
{
printf("%d,",p->data);
p = p->next;
} while ( p != NULL);
}