Topic
Enter a sequence of two integers, the first sequence represents the stacking order of the stack, determine whether the second sequence is the first stack of the stack sequence, assuming that all the numbers in the stack are unequal, for example:
into the stack sequence {1,2,3,4,5}
Out Stack sequence 1{4,5,3,2,1}
Out Stack sequence 2{4,3,5,1,2}
The stack sequence 1 is one of the pop-up results in the stack sequence, and sequence 2 is not.
Analysis
Pop-up sequence the first is 4, so to let the top element of the stack is 4 o'clock pop, so press into the three-to-one, until 4 appears on the top of the stack, sequence 1 The second is 5, the stack top to have 5 exist just line, no, continue to press into 5, and then pop, the data stack is three-in-one 2, 1, can be ejected sequence 1, and sequence 2, first pressed into the 1,2,3,4, after the popup 4, 3, press into 5, pop 5, again when the 2,1 is the order, sequence 2 does not conform, so, sequence 2 is not one of the stack sequence.
"Test Code"
#include <stdio.h>#include <stdlib.h>#define OK 1#define ERROR 0#define MAX TentypedefintMy_data;typedefintstack_data;typedef struct stacknode{stack_data data; struct Stacknode*next;} My_stack, * my_stack_ptr;typedef struct linkstack{my_stack_ptr top;//The top of the stack is a pointerintCount;} Linkstack;void Init (linkstack*s{My_stack_ptr first = (my_stack_ptr) malloc (sizeof (my_stack)); First->Next= NULL;s->top = First;s->count =0;}intStack_empty (Linkstack*s){if(s->top->Next==null)returnOK;Else returnERROR;}int Push(Linkstack*s, My_data*e{My_stack_ptr pnew = (my_stack_ptr) malloc (sizeof (my_stack)); Pnew->data =*e; Pnew->Next=s->top;s->top = pnew;s->count++;returnOK;}int Pop(Linkstack*s, My_data*e) {my_stack_ptr p;if(Stack_empty (s))returnERROR;*e=s->top->data; p =s->top;s->top =s->top->Next; Free (p);s->count--;returnOK;}intTestint *in,int *out,int length){if(in = = NULL | | out = = NULL)return 0; Linkstack*s= (linkstack*)malloc (sizeof (linkstack)); My_data*e= (my_data*)malloc (sizeof (my_data)); Inits);inti =0;intj =0; while(j<length) { while(Stack_empty (s)||s->top->data! = out[j]&& i<length) {Push(s, &in[i]); ++i; }if(s->top->data = = Out[j]) {Pop(s, e); ++j; }Else return 0; }return 1; }void Main () {Linkstack*s= (linkstack*)malloc (sizeof (linkstack)); My_data*e= (my_data*)malloc (sizeof (my_data));intSequence_in[] = {1,2,3,4,5};intSequence_out1[] = {4,5,3,2,1};intSequence_out2[] = {4,3,5,1,2};if(Test (sequence_in, SEQUENCE_OUT1,5))printf("{4,5,3,2,1} is one of the {1,2,3,4,5} pop-up sequences \ n");Else printf("{4,5,3,2,1} is not one of the {1,2,3,4,5} pop-up sequences \ n");if(Test (sequence_in, Sequence_out2,5))printf("{4,3,5,1,2} is one of the {1,2,3,4,5} pop-up sequences \ n");Else printf("{4,3,5,1,2} is not one of the {1,2,3,4,5} pop-up sequences \ n");}
"Output Results"
Stack push-in, pop-up sequence