TNode *NodeExchange(TNode *pHead, int pExcN1, int pExcN2)
{
TNode * pTemp = pHead;
//1.节点位置传入相同
if(pExcN1 == pExcN2) return pHead;
TNode *p1 = nullptr,*p1Pre = nullptr,*p1Cur = nullptr,
*p2 = nullptr, *p2Pre = nullptr,*p2Cur = nullptr;
for (int i = 0; (pHead = pHead->pNext) != nullptr; i++)
{
if (i == (pExcN1-1))
{
p1Pre = pHead;
p1 = p1Pre->pNext;
p1Cur = p1->pNext;
}
if (i == (pExcN2-1))
{
p2Pre = pHead;
p2 = p2Pre->pNext;
p2Cur = p2->pNext;
}
}
//2.相邻接点
if (abs(pExcN2-pExcN1) == 1)
{
p1Pre->pNext = p2;
p1->pNext = p2Cur;
p2->pNext = p1;
}
//3.非相邻接点
else
{
p1Pre->pNext = p2;
p1->pNext = p2Cur;
p2Pre->pNext = p1;
p2->pNext = p1Cur;
}
return pTemp;
}
单向链表交换节点
最新推荐文章于 2024-09-11 19:35:36 发布