双栈排序

题目:假设给出一个数组:{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;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值