题目:假设给出一个数组:{5,6,4,2,3},使用堆栈,如何将其排序为{2,3,4,5,6}?
思路:
使用两个堆栈,一个堆栈s1存储原数组,另一个堆栈s2作为过渡栈;
使用调度场算法,不断地重复一个过程:将s1栈顶的值tmp出栈,与s2栈顶值比较,若是大于s2,则将其压入s2,否则将其压入s2栈尾,压入栈尾需要先将s2中的值压入s1,再压入tmp(此时s2只有tmp 一个元素,原来s2中元素已全部在s1中。此时只有栈底为tmp)。
代码:
#include <stdio.h> #include <stdlib.h> typedef struct NODE{ struct NODE * next; int data; }node; typedef struct STACK{ node * head; int len; }stack; stack * init(void){ stack * List=(stack *) malloc(sizeof(stack)); List->head=NULL; List->len=0; return List; } int pop(stack *st){ if(0>=st->len||NULL == st) { printf("NULL stack,leaving now\n"); exit(1); } int pdata=st->head->data; st->head=st->head->next; st->len--; return pdata; } void push(stack *st, int n){ if(NULL == st|| 0>st->len){ printf("wrong stack,please check the source code, now leaving\n"); exit(1); } node * pp=(node*)malloc(sizeof(node)); pp->next=st->head; pp->data=n; st->head=pp; st->len++; } void print(stack*st,int n){ node * pp=st->head; while(n){ printf("%d\n",pp->data); n--; pp=pp->next; } } int main(){ int tmp,tmp1; stack * st1=init(); stack * st2=init(); int n=0; push(st1,3); n++; push(st1,2); n++; push(st1,4); n++; push(st1,6); n++; push(st1,5); n++; print(st1,n); tmp=pop(st1); push(st2,tmp); while(0!=st2->len) { if(0>=st1->len){ while(0!=st2->len){ tmp1=pop(st2); push(st1,tmp1); } break; }else{ tmp=pop(st1); if( tmp >= st2->head->data) push(st2,tmp); else{ while(0!=st2->len){ tmp1=pop(st2); push(st1,tmp1); } push(st2,tmp); } } } printf("\n\n"); print(st1,n); return 0; }