Given a liked list, I'd like to swap every pair of nodes as follows:
input: a-b-c-d-e-f-g
output: b-a-d-c-f-e-g
If there's an odd number of nodes then the last node is tacked on as-is. This should be done in-place. Implement the method: Node* SwapTo(Node* start)
I'm using this Node definition:
class Node {
public:
char data;
Node* next;
};
Here's the unoptimized recursive solution:
Node* SwapTwo(Node* start) {
if (!start) {
return start;
}
Node* second = start->next;
if (!second) {
return start;
}
Node* third = second->next;
second->next = start;
start->next = SwapTwo(third);
return second;
}
What is the tail-recursive solution?