您的位置:首页 > 其它

链表2

2016-05-07 23:35 267 查看
// 约瑟夫环问题
PSListNode JosephCircle(PSListNode pHead, int M);

// 单链表逆置:两种方法都实现:一、三个指针  二、尾插发
void ReverseList(PSListNode* pHead);

// 单链表排序:冒泡(优化版本)
void SortList(PSListNode pHead);

// 查找链表的倒数第K个结点
PSListNode FindLastKNode(PSListNode pHead, int K);

// 判断链表是否带环
PSListNode HasCycle(PSListNode pHead);

// 求环的长度
int GetCyleLen(PSListNode pMeetNode);

// 合并两个已序单链表
PSListNode MergeList(PSListNode pL1, PSListNode pL2);

typedef int DataType;
typedef struct ListNode
{
DataType data;
struct ListNode *pNext;
}SListNode, *PSListNode;

// 约瑟夫环问题
PSListNode JosephCircle(PSListNode pHead, int M)
{
PSListNode pNode = pHead;
PSListNode pDelNode;
int K = M;
if (pHead == NULL || M <= 0)
{
return NULL;
}
while (pNode->pNext != pNode)//不是它本身
{
K= M;
while (--K)
{
pNode = pNode->pNext;//头结点的指针域
}
pDelNode = pNode->pNext;
pNode->data = pDelNode->data;
pNode->pNext = pDelNode->pNext;
free(pDelNode);
}
}

// 单链表逆置:两种方法都实现:一、三个指针  二、尾插发
void ReverseList(PSListNode* pHead)
{
PSListNode pNode = NULL;
PSListNode pPreNode = NULL;
PSListNode pNewHead = NULL;
assert(NULL != pHead);
if ((*pHead == NULL) || (*pHead->pNext == NULL))
{
return;
}
pNode = *pHead;
while (pNode)
{
pPreNode = pNode;
pNode = pNode->pNext;
pPreNode->pNext = pNewHead;
pNewHead = pPreNode;
}
*pHead = pNewHead;
}

// 单链表排序:冒泡(优化版本)
void SortList(PSListNode pHead)
{
PSListNode pNode = NULL;
PSListNode pTai1Node = NULL;
PSListNode pPreNode = NULL;
if (pHead == NULL)
{
return;
}
//外;循环次数
//具体冒泡
while (pHead != pTai1Node)
{
pNode = pHead;
while (pNode->pNext!=NULL)
{
pPreNode = pNode;
pNode = pNode->pNext;
if (pPreNode->data > pNode->data)
{
DataType temp = pPreNode->data;
pPreNode->data = pNode->data;
pNode->data = temp;
}
}
pTai1Node = pNode;
}
}

// 查找链表的倒数第K个结点
PSListNode FindLastKNode(PSListNode pHead, int K)
/*返回倒数第k个结点*/
{
assert(pHead);
/*1、k大于head的长度
2、*/
PSListNode pSlow = pHead;
PSListNode pFast = pHead;
int k;
while (k--)
{
if (pFast == NULL)
{
return NULL;
}
else
{
pFast = pFast->pNext;
}
}
while (pFast)
{
pSlow = pSlow->pNext;
pFast = pFast->pNext;
}
return pSlow;
}

// 判断链表是否带环
PSListNode HasCycle(PSListNode pHead)
{
PSListNode pSlow = pHead;
PSListNode pFast = pHead;

while (pFast&& pFast->pNext)
{
pSlow = pSlow->pNext;
pFast = pFast->pNext->pNext;
if (pSlow == pFast)
break;
}
return !(pFast == NULL || pFast->pNext == NULL);
}

// 合并两个已序单链表
PSListNode MergeList(PSListNode pL1, PSListNode pL2)
{
PSListNode pNewHead = NULL;
PSListNode pL1Node = pL1;
PSListNode pL2Node = pL2;
PSListNode pNode = NULL;
PSListNode pTai1Node = NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表问题