This article describes the C + + based on stack to achieve rail problems. Share to everyone for your reference. The specific analysis is as follows:
The sample diagram looks like this:
Classic Stack problem! The first time to do the thinking is too confusing, now read the Liu Rugia book, rearrange.
#include <stdio.h> #include <string.h>/************************************************************** * Use array A to store the pre-adjusted compartment number sequence, array B to store the adjusted compartment number sequence * Use stack stack to store the compartment in transit c * Use the ix_a to point to the front compartment of a, with ix_b pointing to the front of the carriage * * If Ix_b has pointed to the, then all The carriage has been in the specified order, otherwise * if the Ix_b pointed to the carriage equal to the ix_a-pointed carriage, then directly to the ix_a open to B, otherwise * if the ix_b point of the car is equal to stack elements in stack, then the stack out of the top of the car, otherwise * if there is a car, then the A into the transit station C
, otherwise * output has no solution.
/char stack[1010];
Char a[1010];
Char b[1010];
int main (int argc, char *argv[]) {scanf ("%s%s", a,b);
int len_a = strlen (a);
int len_b = strlen (b);
/* Initialize stack */int top =-1;
int tot = 0;
int ix_a = 0;
int ix_b = 0;
while (1) {if (a[ix_a] = = B[ix_b]) {printf ("in\n");
printf ("out\n");
++ix_b;
++ix_a;
if (Ix_b = = len_b)/* The car has been all out, operation success/break;
else if (tot!= 0/* First check the stack for null/&& B[ix_b] = = Stack[top]) {printf ("out\n");
--tot;
--top;
++ix_b;
if (Ix_b = = Len_b) break;
else if (ix_a!= len_a) {printf ("in\n");
++tot;
++top;
Stack[top] = a[ix_a];
++ix_a;
if (Ix_b = = Len_b) break; else {printf (no solution!)
\ n ");
return 0; } printf (Finish!
\ n ");
return 0; }
I hope this article will help you with your C + + programming.