## paulj91

BAN USERbuckCherry speaks the truth, this solution will NOT perform as well as its iterative counterpart due to its recursive nature. Hopefully this algorithm gives a clearer picture of what is actually going on in the iterative solution and makes it easier to understand, but remember to favor iteration over recursion when possible (like in an application using this algorithm)

- paulj91 November 12, 2012Warning: this method is pretty inefficient, but it should work.

```
for i in range (8):
for j in range(8):
if i != j:
for k in range (8):
if k == i:
string = string + r"\d"
elif k == j:
string = string + r"[a-zA-Z]"
else:
string = string + r"."
if i != 7 or j != 6:
string = string + r"|"
```

String will be your regular expression at the end

Essentially, this determines all possible positions of the two necessary characters, and creates a regular expression that takes them into account. I'd advise against this method if you can think of a better manner, but it should produce a working regex.

Edit: Another method using a couple of regexes, run

`"^........$"`

as your first regular expression.

After this, run the second expression which another user listed above:

`".*\d+.*[a-zA-Z]+.*|.*[a-zA-Z]+.*\d+.*"`

Still looking for a single expression that is more efficient than the previous one I listed, no luck so far.

- paulj91 October 25, 2012```
Node* swap(Node* head)
{
if (head == NULL || head -> next == NULL)
return head;
Node* temp = head;
head = head -> next;
Node* succ = head -> next;
head -> next = temp;
temp -> next = swap(succ);
return head;
}
```

This method is pretty straightforward if we just treat the nodes as pairs. Assuming we have at least one pair of nodes remaining, we can swap them. We set "succ" to the next node AFTER the pair we are looking at, swap the two nodes in our pair, then link the new second element to the properly swapped set of nodes that follow. To make sure the rest of the nodes are swapped, we just make sure to linked to the SWAPPED successor from our new second node.

Then, if it turns out we don't have a valid pair, that's our base case. If we have one node, then we don't need to worry about swapping, so we just return that node. If we don't have any, then we return NULL, since it's the end of our swapped list.

Just call "head = swap(head)", or wrap that up in a function, and your list should swap.

**CareerCup**is the world's biggest and best source for software engineering interview preparation. See all our resources.

buckCherry:

- paulj91 November 20, 2012I meant to say that Anonymous' solution would perform better than my listed solution for large data sets because of *my* solutions recursive nature, not any recursive nature of Anonymous' algorithm.