//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).
#include <iostream>
using namespace std;
#define threshold 1
struct StackNode{
int value;
StackNode * next;
StackNode(int v)
{
value = v;
next = NULL;
}
};
class Stack
{
private:
StackNode * head;
public:
Stack()
{
head = NULL;
}
~Stack()
{
while (head != NULL)
{
StackNode * node = head;
head = head->next;
delete node;
}
head = NULL;
}
void push(int value)
{
StackNode * node = new StackNode(value);
if (head == NULL)
head = node;
else
{
node->next = head;
head = node;
}
}
int pop()
{
if (head == NULL)
{
cout<<"eeerror"<<endl;
return -1;
}
StackNode * node = head;
int value = node->value;
head = head->next;
delete node;
return value;
}
int top()
{
if (head != NULL)
return head->value;
else
{
cout<<"NULL"<<endl;
return -1;
}
}
bool isEmpty()
{
return head == NULL;
}
};
class SetOfStacks
{
private:
Stack head;
int num;
public:
SetOfStacks()
{
num = 0;
}
~SetOfStacks()
{
while (!head.isEmpty())
{
StackNode * h = (StackNode *)head.pop();
while (h != NULL)
{
StackNode * node = h;
h = h->next;
delete node;
}
}
}
void push(int value)
{
if (head.isEmpty())
{
StackNode * h = new StackNode(value);
head.push((unsigned int)h);
num ++;
}
else
{
if (num < threshold)
{
StackNode * h = (StackNode *)head.pop();
StackNode * node = new StackNode(value);
node->next = h;
h = node;
head.push((unsigned int)h);
num ++;
}
else
{
StackNode * h = new StackNode(value);
head.push((unsigned int)h);
num = 0;
}
}
cout<<"Insert finished"<<endl;
}
int pop()
{
if ((StackNode *)head.top() == NULL)
{
cout<<"Error"<<endl;
return -1;
}
StackNode * h = (StackNode *)head.pop();
StackNode * node = h;
int value = node->value;
h = h->next;
delete node;
if (h != NULL)
head.push((unsigned int)h);
num --;
return value;
}
int top()
{
if (head.isEmpty())
cout<<"eerror"<<endl;
StackNode * h = (StackNode *)head.top();
int value = h->value;
return value;
}
};
int main()
{
SetOfStacks s;
s.push(3);
s.push(4);
s.push(5);
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
return 0;
}
crack the code interview 3.3
最新推荐文章于 2019-04-22 14:02:16 发布