careercup3.3

没有太多技巧,但感觉程序有点乱。当然用vector中总是随机访问代价其实还是不小的(虽然是O(1)),数据大会很慢,还是数组好。。总之。。。劳动节码代码最光荣

/*Imagine a (literal) stack of plates   If the stack gets too high, it might topple   There-
fore, in real life, we would likely start a new stack when the previous stack exceeds 
some threshold   Implement a data structure SetOfStacks that mimics this   SetOf-
Stacks should be composed of several stacks, and should create a new stack once 
the previous one exceeds capacity   SetOfStacks push() and SetOfStacks pop() should 
behave identically to a single stack (that is, pop() should return the same values as it 
would if there were just a single stack) 
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific 
sub-stack
*/
#include <iostream>
#include <vector>
#include <iterator>
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;
	int size;
	Stack():top(0),size(0){	}
	~Stack();

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

class SetofStack{
public:
	vector<Stack*> s;//stack* is necessary
	int capacity;
	SetofStack(int k = 10):capacity(k){
		s.push_back(new Stack);
	}
	SetofStack(int ar[],int ca,int n):capacity(ca){
		s.push_back(new Stack);
		for(int i = 0; i<n; i++)
			push(ar[i]);	
	}
    
	Node* pop();
	void push(int);
	Node* findtop(){ return s[s.size()-1]->top;}
	void print() {
		for(vector<Stack*>::reverse_iterator it= s.rbegin(); it != s.rend(); it++)
    		(*it)->print();
	}
	Node* popAt(int);
};

Stack::~Stack(){
	while(top){
	   Node* p =pop();
	   delete p;
	}
}

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

	Node* p = top;
	top = top->next;
	return p;
	size--;
}

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

Node* SetofStack::pop(){
	int id = s.size() - 1;
	
	if(s[id]->size == 0){
		s.pop_back();
		id--;
	}
	return s[id]->pop();
}

void SetofStack::push(int k){
	int id = s.size() - 1;
	
	if (s[id]->size == capacity){
	   s.push_back(new Stack);
	   id++;
	}
	s[id]->push(k);
}

Node* SetofStack::popAt(int k){
	Node* ss = s[k-1]->top;

	for(int i = k;i< s.size();i++){
		Node* p = s[i]->top;
		Node* np = p->next;
		while (np && np->next){
			p = np;
			np = np->next;
		}
		p->next = 0;
		np->next = s[i-1]->top->next;
		s[i-1]->top = np;
	}
	return ss;

}

int main(){
	int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
	SetofStack ll(ar,6,16);
	ll.print();
	ll.popAt(1);
	ll.print();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值