1. 单向链表的逆序:
int Is_Empty_Link(LINK_LIST *plist)
{
return plist->phead == NULL;
}
void Reverse_Link(LINK_LIST *plist)
{
LINK_NODE *ptmp = plist->phead;
LINK_NODE *pinsert = NULL;
plist->phead = NULL;
if(Is_Empty_Link(plist))
{
return;
}
else
{
while(ptmp != NULL)
{
pinsert = ptmp;
ptmp = ptmp->pnext;
pinsert->pnext = plist->phead;
plist->phead = pinsert;
}
}
return;
}
在这里的逆序,利用了头插法的思想,因为利用头插法插入数据,数据是逆序插入的,最后插入的数据在最前面,最先插入的数据在最后面,那么逆序也可以使用这个思想。
2. 删除单向链表的某个结点
int Delete_Link_Node(LINK_LIST *plist, DATA_TYPE data)
{
if(Is_Empty_Link(plist))
{
return 0;
}
LINK_NODE *pfree = plist->phead;
LINK_NODE *ppre = NULL;
int del_cnt = 0;
while(pfree != NULL)
{
if(pfree->data == data)
{
if(pfree == plist->phead)
{
plist->phead = pfree->pnext;
free(pfree);
pfree = plist->phead;
}
else
{
ppre->pnext = pfree->pnext;
free(pfree);
pfree = ppre->pnext;
}
plist->curlen--;
del_cnt++;
}
else
{
ppre = pfree;
pfree = pfree->pnext;
}
}
return del_cnt;
}
可以发现这段代码可以将所有数据为data的链表结点都删除了,如果只想删除第一个的话,那就在找到第一个数据为data的结点以后,将结点free掉,然后直接return,那么程序就实现了只删除第一个。
3. 实现单向链表的升序排序(插入排序的思想)
int Insert_Sort_Link(LINK_LIST *plist)
{
LINK_NODE *pinsert = NULL;
LINK_NODE *ptmp = plist->phead;
plist->phead->pnext = NULL;
while(ptmp != NULL)
{
pinsert = ptmp;
ptmp = ptmp->pnext;
if(pinsert->data <= plist->phead->data)
{
pinsert->pnext = plist->phead;
plist->phead = pinsert;
}
else
{
LINK_NODE *perg = plist->phead;
while(perg->pnext != NULL && pinsert->data >= perg->pnext->data)
{
perg = perg->pnext;
}
pinsert->pnext = perg->pnext;
perg->pnext = pinsert;
}
}
return 0;
}