栈的应用
输入一串字符串只包含S和H,把全部的H排到S的后面,运行时没反应,麻烦高手指点一下#include <stdio.h>
#include <stdlib.h>
typedef struct node{
char data;
struct node *next;
}node,*link;
typedef struct{
link top;
link base;
}stack;
int initstack(stack *s)
{s->base=(link)malloc(sizeof(node));
if(!s->base) return(-1);
s->top=s->base;
s->top->next=NULL;
return 1;
}
int stackempty(stack *s)
{if(s->top==s->base) return 1;
else return 0;
}
int push(stack *s,char e)
{link p;
p=(link)malloc(sizeof(node));
if(!p) return(-1);
p->data=e;
p->next=s->top;
s->top=p;
return 1;
}
int pop(stack *s,char *e)
{if(!s->top) return 0;
link p;
p=s->top;
*e=p->data;
s->top=p->next;
free(p);
return *e;
}
void trainarrange(char *train)
{
char *p,*q,*t,c;
stack s;
p=train;
q=train;
t=q;
initstack(&s);
while(*p)
{
if(*p=='H')
push(&s,*p);
else
{
*(q++)=*p;
p++;
}
}
while(!stackempty(&s))
{
pop(&s,&c);
*(q++)=c;
}
while(t!='\0')
{
printf("%c",*t);
t++;
}
}
main()
{ char a[5];
int i=0;
char *train;
do
{
scanf("%c",&a[i]);
i++;
}while(i!='#');
train=a;
trainarrange(train);
}