您的位置:首页 > 其它

careercup3.6

2012-05-04 15:53 176 查看
把全局的排序做成每个子问题的排序,每次出来的一个数都会排好序。

/*Implement a MyQueue class which implements a queue using two stacks
*/
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){this->next = 0;}
Node(int a, Node* n=0):data(a),next(n){}
};

class Stack{
public:
Node* top;
Stack():top(0){	}
Stack(int ar[], int l){
top = 0;
for(int i = 0; i<l; i++)
this->push(ar[i]);
}
~Stack();

int pop();
void push(int);
void print()const{
Node* p = top;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
};

Stack::~Stack(){
while(top){
this->pop();
}
}

int Stack::pop(){
if(!top) return 0;

Node* p = top;
top = top->next;
int k = p->data;
delete p;
return k;
}

void Stack::push(int k){
Node* p = top;
top = new Node(k,p);
}

Stack* sort(Stack s){
Stack* temp = new Stack();
while(s.top){
int k = s.pop();
while(temp->top && temp->top->data >k)
s.push(temp->pop());
temp->push(k);
}
return temp;
}
int main(){
int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
Stack ll(ar,16);
sort(ll)->print();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: