Problem
There is a $N$ by $1$ long card consisting of $N$ square cards, each having the number $1, 2, \cdots, N$ regardless of the sequence of cards. Find whether or not the long card could be in order, by folding it either backward or forward. (Suppose that there is no consideration of thickness of cards).
For example, there is a long card is a sequence of $\{5,3,2,1,4\}$. Then if we can make it in order by folding like the following:

I know my picture is not seen as the square cards set. However, my poor English cannot describe this problem well. I hope to make C-code or Matlab-code solving this problem. When a sequence is given, I want to check the sequence can be done like above or not(i.e. I want to display "Yes" or "No").
Sorry and thank you for reading my question.
I think this problem may be similar to figuring out whether a maze is a simple alternating transit maze: http://www.math.stonybrook.edu/~tony/mazes/satmaze.html
In that case the solution would be whether when you write the numbers out like this: $n_1 n_2\cdots n_N$, you can draw a line that visits the numbers $1\cdots N$ in order, passing alternatingly above and below the number line, without crossing itself.
If I can produce reasonable code for this, I will submit it as well.