完成链表的以下操作:
// 使用冒泡对单链表进行排序
void BubbleSort(PNode pHead)
// 合并两个已序链表,合并之后新链表依然有序
PNode MergeList(PNode pHead1, PNode pHead2)
// 查找无头单链表的倒数第K个结点
PNode FindLastKNode(PNode pHead, int K);
// 删除无头单链表的倒数第K个结点
PNode DeleteLastKNode(PNode pHead, int K);
// 判断链表是否带环,如果带环求环的长度,并给出入口点
PNode HasCircle(PNode pHead);
int GetCircleLen(PNode pHead);
PNode GetEnterNode(PNode pHead, PNode pMeetNode);
源程序
void BubbleSort(PNode pHead)//冒泡排序
{
if (NULL == pHead || NULL == pHead->next)
{
return;
}
PNode pCur = pHead;
PNode pTail = NULL;
int flag = 0;
while (pTail != pHead)
{
pCur = pHead;
while (pCur->next != pTail)
{
if (pCur->data > pCur->next->data)
{
DataType tmp = pCur->data;
pCur->data = pCur->next->data;
pCur->next->data = tmp;
flag = 1;
}
pCur = pCur->next;
if (!flag)
{
return;
}
}
pTail = pCur;
}
}
PNode FindLastKNode(PNode pHead, int K)
{
if (NULL == pHead || K == 0)
{
return NULL;
}
PNode pSlow = pHead;
PNode pFast = pHead;
while (--K)
{
if (NULL == pFast)
{
return NULL;
}
pFast = pFast->next;
}
while (pFast->next)
{
pSlow = pSlow->next;
pFast = pFast->next;
}
return pSlow;
}
void DeleteLastKNode(PNode pHead, int K)
{
if (NULL == pHead || K == 0)
{
return;
}
PNode pos = FindLastKNode(pHead, K);
Erase(pHead, pos);
PNode MergeList(PNode pHead1, PNode pHead2);
考虑以下因素:
pHead1为空—–返回pHead2
pHead2为空—–返回pHead1
当pHead1和pHead2都不为空时,分析如图示:
PNode MergeList(PNode pHead1, PNode pHead2)
{
if (NULL == pHead1)
{
return pHead2;
}
if (NULL == pHead2)
{
return pHead1;
}
PNode newNode = NULL;
PNode pTail = NULL;
if (pHead1->data < pHead2->data)
{
pTail = pHead1;
pHead1 = pHead1->next;
}
else
{
pTail = pHead2;
pHead2 = pHead2->next;
}
newNode = pTail;
while (pHead1 && pHead2)
{
if (pHead1->data < pHead2->data)
{
pTail->next = pHead1;
pTail = pHead1;
pHead1 = pHead1->next;
}
else
{
pTail->next = pHead2;
pTail = pHead2;
pHead2 = pHead2->next;
}
}
if (pHead1)
{
pTail->next = pHead1;
}
else
{
pTail->next = pHead2;
}
return newNode;
}
// 判断链表是否带环,若带环给出相遇点
PNode HasCircle(PNode pHead)
{
if (pHead == NULL)
{
return NULL;
}
else
{
PNode pFast = pHead;
PNode pSlow = pHead;
{
while (pFast && pFast->next)
{
pSlow = pSlow->next;
pFast = pFast->next->next;
if (pFast == pSlow)
{
return pSlow;
}
}
return NULL;
}
}
}
// 求环的长度
int GetCircleLen(PNode pMeetNode)
{
PNode pCurNode = pMeetNode;
int count = 1;
while (pCurNode->next != pMeetNode)
{
pCurNode = pCurNode->next;
count++;
}
return count;
}
// 求环的入口点
PNode GetEnterNode(PNode pHead, PNode pMeetNode)
{
if (pHead == NULL)
{
return NULL;
}
else
{
PNode pFast = pHead;
PNode pSlow = pMeetNode;
{
while (pFast != pSlow)
{
pSlow = pSlow->next;
pFast = pFast->next;
}
return pSlow;
}
}
}