// Left-K node is the node k spaces from the head.
// Right-K node is the node k spaces from the tail.
// Add a temporary head node before head. In case
// Left-K node is first node.
ListNode* tempHead = new ListNode(-100);
tempHead->next = head;
head = tempHead;
// Find size of list.
int listNodeCount = 0;
ListNode* cur = head->next;
ListNode* prev = head;
while(cur != nullptr)
{
++listNodeCount;
prev = cur;
cur = cur->next;
}
// Need the Left-K node to be to the left of the Right-K node.
// Say ACount is the number spaces to the Left-K node, and
// say BCount is the number of spaces to the Right-K node.
int ACount = std::min(k, listNodeCount - k + 1);
int BCount = std::max(k, listNodeCount - k + 1);
// If the Left-K node is the same as the Right-K node algorithm
// doesn't work, so if statement. Just return the real head.
if(ACount == BCount)
{
return head->next;
}
// ListNode pointers.
// Set ListNode pointers for left and right pointers.
// A is the left pointer, B is the right pointer.
ListNode* preA = nullptr;
ListNode* A = nullptr;
ListNode* postA = nullptr;
ListNode* preB = nullptr;
ListNode* B = nullptr;
ListNode* postB = nullptr;
int curCount = 1;
cur = head->next;
prev = head;
while(cur != nullptr)
{
if (curCount == ACount)
{
preA = prev;
A = cur;
postA = cur->next;
}
if (curCount == BCount)
{
preB = prev;
B = cur;
postB = cur->next;
break;
}
prev = cur;
cur = cur->next;
++curCount;
}
// Finally algorithm starts.
// Case where A->next == B.
if(A->next == B)
{
postA = A;
preB = B;
}
preA->next = B;
A->next = postB;
B->next = postA;
preB->next = A;
return head->next;
}
};