单链表的环操做

2021年09月15日 阅读数:1
这篇文章主要向大家介绍单链表的环操做,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

链表介绍:ide

链表概念--链表是一种线性表,可是并非顺序存储,而是每一个节点里面存储着下一个节点的指针,把存储数据元素的数据串链起来。url

单链表的环操做_单链表单链表演示图:单链表的环操做_ 带环链表_02spa


建立结构体指针

typedef int DataType;blog

typedef struct ListNodeget

{it

DataType data;io

struct ListNode *pNext;class

}SListNode, *PSListNode;List



求环入口点:


单链表的环操做_单链表单链表的环操做_单链表单链表的环操做_单链表_05


PSListNode FindEnterNode(PSListNode pHead, PSListNode pMeetNode)

{

PSListNode pNode1 = pHead;

PSListNode pNodeM = pMeetNode;

if (pHead == NULL || pMeetNode == NULL)

{

return NULL;

}

while (pNode1 != pNodeM)

{

pNode1 = pNode1->pNext;

pNodeM = pNodeM->pNext;

}

return pNode1;

}


判断两个链表


是否相交:


单链表的环操做_ 带环链表_06


int IsListCroseWithCycle(PSListNode pL1, PSListNode pL2)

{

PSListNode pL1MeetNode = NULL;

PSListNode pL2MeetNode = NULL;

PSListNode pL1Node = pL1;

PSListNode pL2Node = pL2;

PSListNode pNode = NULL;

if (pL1 == NULL || pL2 == NULL)

{

return 0;

}

pL1MeetNode = HasCycle(pL1Node);

pL2MeetNode = HasCycle(pL2Node);


//都不带环

if (pL1MeetNode == NULL && pL2MeetNode == NULL)

{

while (pL1Node->pNext != NULL)

{

pL1Node = pL1Node->pNext;

}

while (pL2Node->pNext != NULL)

{

pL2Node = pL2Node->pNext;

}

if (pL1Node == pL2Node)

{

return 1;

}

return 0;

}


//两个都带环

if (pL1MeetNode != NULL && pL2MeetNode != NULL)

pNode = pL1MeetNode;

{

while (pNode->pNext != pL1MeetNode)

{

if (pL2MeetNode == pNode)

{

return 1;

}

pNode = pNode->pNext;

}

return 0;

}

}