Hamed Kiani (Ph.D.)
  • Home
  • Publications
  • Contact

Write a program to sort a stack in ascending order. c++

9/15/2015

0 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

Write a program to sort a stack in ascending order.
You should not make any assumptions about how the stack is implemented.
The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.

peek: return the top value of stack without removing it.

We use two stacks for ordering the elements. The main stack contains the elements in a sorted fashion. 
The auxulary stack is used to sort the elements of the main stack if required. 
memory  O(n)
time       O(n^2)

Questions:

how can we write this function with the memory of O(1)?
how about a time of O(n)? is that possible?


By: Hamed Kiani (Sep. 14, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;

class sortedStack{

private:
        int *_mainStack;     // main ordered stack
        int *_auxStack;              // auxulary stack for ordering
        int _size;                       // the max size of stack for overflow checking
        int _top;                        // index of the top element of main stack
        int _aux_top;            // index of the top element of aux stack

public:
        sortedStack(int n);      // constructor
        ~sortedStack();             // destructor
        bool isEmpty();           // is the stack empty?
        bool isFull();            // is the stack full?
        void push(int data);       // ordered push
//         void ordered_push(int data);
        void pop();                       // normal pop operation
        int peek();                       // peek function   
        void print();             // print the main stack
};

////////////////////////////////////////////////////////////
sortedStack::sortedStack(int n)
{
        _size = n;
        _top = -1;
        _aux_top = -1;
        // initializaing the main and aux stacks
        _mainStack = (int*) malloc(sizeof(int) * _size);
        _auxStack  = (int*) malloc(sizeof(int) * _size);
}

////////////////////////////////////////////////////////////
sortedStack::~sortedStack()
{
        free(_mainStack);
        free(_auxStack);        
}

////////////////////////////////////////////////////////////
bool sortedStack::isEmpty()
{
        return (_top == -1);
}

////////////////////////////////////////////////////////////
bool sortedStack::isFull()
{
        return (_top == _size-1);
}

////////////////////////////////////////////////////////////
void sortedStack::push(int data)
{
        // is full, not possible to push a new element
        if (isFull())
        {
                cout << " stack overflow!" << endl;
                return;
        }
        // if the stack is empty or the new element is smaller 
        //  than the top value just do simple push
        int top_data = peek();
        if ((data >= top_data) | (isEmpty()))
        {
                _mainStack[++_top] = data;
                return;
        }

        // otherwise, use aux-stack to push the new element in the right place
        while(~isEmpty() & (top_data > data ))
        {
                _auxStack[++_aux_top] = top_data;
                pop();
                top_data = peek();
        }
        _mainStack[++_top] = data;
        // re-push the lements in aux-stack back to the main stack
        while(_aux_top >= 0)
        {
                _mainStack[++_top] = _auxStack[_aux_top--];         
        }
        return;
}

////////////////////////////////////////////////////////////
void sortedStack::pop()
{
        if (isEmpty())
        {
                cout << " stack unerflow!" << endl;
                return;
        }
        _top--;
}

////////////////////////////////////////////////////////////
int sortedStack::peek()
{
        if (isEmpty())
        {
                cout << " stack is empty!" << endl;
                return INT_MAX;
        }
        return _mainStack[_top];
}

void sortedStack::print()
{
        if (isEmpty())
        {
                cout << " stack is empty!" << endl;
                return;
        }
        cout << " the elemets of stack " << endl;
        for (int i=0; i<=_top; i++)
                cout << _mainStack[i] << " " ;
        cout << endl; 
}

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

int _tmain(int argc, _TCHAR* argv[])
{
        sortedStack myStack(10);
        myStack.push(1);
        myStack.push(15);
        myStack.push(32);
        myStack.push(4);
        myStack.push(1);
        myStack.print();        
        myStack.pop();
        myStack.pop();
        myStack.push(77);
        myStack.push(10);
        myStack.pop();
        myStack.push(-15);   
        myStack.print();        
        return 0;
}
0 Comments

Implement a MyQueue class which implements a queue using two stacks : c++

9/7/2015

0 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

Implement a MyQueue class which implements a queue using two stacks.
We use two stacks, s1 and s2 for enqueue and dequeue. 
 
By: Hamed Kiani (Sep. 7, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;

struct Node{
        int data;
        Node *next;
};

class MyQueue{
private:
        Node *_s1_head;     // enQueue is done using s1
        Node *_s2_head;     // s2 is used for dequeue
        int _s1_size;    // the size of s1 stack    
        int _s2_size;    // the size of s2 stack
        
public:
        MyQueue();
        ~MyQueue();
        void enQueue(int data);    // enqueue data value using s1
        Node* deQueue();             // dequeue using s1 and s2
        void print_s1();          // print elements of s1 stack
        void print_s2();          // print elements of s2 stack
        bool isEmpty(Node *); // check if s1 or s2 are empty
        int get_s1_size(){return _s1_size;}        // return size of s1
        int get_s2_size(){return _s2_size;}        // return size of s2
};

////////////////////////////////////////////////////////////////////
MyQueue::MyQueue()
{
        _s1_head = NULL;
        _s2_head = NULL; 
        _s1_size = 0;
        _s2_size = 0;
        cout << "the stack and queue are initialized! " << endl;
}

////////////////////////////////////////////////////////////////////
MyQueue::~MyQueue()
{
        Node *temp;
        
        while(_s1_head != NULL)
        {
                temp = _s1_head;
                _s1_head = _s1_head->next;
                delete temp;
        }

        while(_s2_head != NULL)
        {
                temp = _s2_head;            
                _s2_head = _s2_head->next;
                delete temp;
        }
        cout << "the stack and queue are deleted! " << endl;
}

////////////////////////////////////////////////////////////////////
// enQueue data at begin of s1 (push s1 stack)
void MyQueue::enQueue(int data)
{
        Node *temp = new Node;
        temp->data = data;
        temp->next = _s1_head;
        _s1_head = temp;
        _s1_size++;  
        cout << " the enQueue value is: " << data << endl;
}

////////////////////////////////////////////////////////////////////
// For deQueue, 
// we copy all from s1 to ss except the last node of s1 O(n)
// re-copy s2 to s1 in reverse order O(n)
// update the s1_size and s2_size
Node* MyQueue::deQueue()
{
        // the queue is empty and dequeue is not possible
        if ((_s1_size == 0) )
        {
                cout<< "dequeue is not possible !" << endl;
                return NULL;                 
        }

        // there is just one element in queue
        if ((_s1_size == 1) )
        {
                Node * temp = _s1_head;
                _s1_head = NULL;
                _s1_size--;
                cout << " the dequeue value is: " << temp->data << endl;
                return temp;
        }

        // there are more than one element in the queue
        _s2_head = _s1_head;
        _s1_head = NULL;
        Node * temp;
        temp = _s2_head;
        _s1_size--;
        while(temp->next->next != NULL)
        {
                temp = temp->next;
        }
        Node * temp2;
        temp2 = temp->next;
        temp->next = NULL;       
        _s1_head = _s2_head;
        _s2_head = NULL;
        cout << " the dequeue value is: " << temp2->data << endl;
        return temp2;
}

////////////////////////////////////////////////////////////////////
void MyQueue::print_s1()
{
        if (_s1_head == NULL)
        {
                cout << " stack s1 is empty" << endl;
                return;
        }
        Node* temp;
        temp = _s1_head;
        while(temp)
        {
                cout << temp->data << " " ;
                temp = temp->next;
        }
        cout << endl;
}

//////////////////////////////////////////////////////////
void MyQueue::print_s2()
{
        if (_s2_head == NULL)
        {
                cout << " stack s2 is empty" << endl;
                return;
        }
        Node* temp;
        temp = _s2_head;
        while(temp)
        {
                cout << temp->data << " " ;
                temp = temp->next;
        }
        cout << endl;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

int _tmain(int argc, _TCHAR* argv[])
{
        MyQueue queue;
        queue.enQueue(1);        
        cout << queue.get_s1_size() << endl;
        cout << queue.get_s2_size() << endl;
        queue.print_s1();
        queue.print_s2();
        Node * temp = queue.deQueue();
        temp = queue.deQueue();
        temp = queue.deQueue();
        temp = queue.deQueue();
        temp = queue.deQueue();
        queue.print_s1();
        queue.print_s2();
        queue.enQueue(3);
        queue.enQueue(4);
        queue.print_s1();
        queue.print_s2();
        return 0;
}
0 Comments

Imagine a (literal) stack of plates.If the stack gets too high, it might topple.Therefore, 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.Implement

9/7/2015

1 Comment

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

Imagine a (literal) stack of plates.
If the stack gets too high, it might topple.
Therefore, 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.
Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.
 
By: Hamed Kiani (Sep. 7, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;

class SetOfStacks{
private:
        int _numOfStk;   // number of stacks
        int _thOfStk;    // threshold of stacks
        int _curStk;     // index of current stack
        int **_stacks;       // two-dim array to keep stacks elements
        int *_elmts; // number of elements in each stack

public:
        SetOfStacks(int n, int t);
        ~SetOfStacks();
        void push(int n);  // push the element n on the stack
        int pop();                        // pop operation
        int pop(int k);            // pop operation from stack k
        bool isFull(int k);        // is stack k full?
        bool isFull();            // is the stack full?
        bool isEmpty(int k);//        is the stack k empty?
        bool isEmpty();           // is the stack empty?
        void printAll();  // print all elements
        void printK(int k);        // print elemets of stack k
};

////////////////////////////////////////////////////////////       
SetOfStacks::SetOfStacks(int n, int t)
{
        _numOfStk = n;
        _thOfStk  = t;
        _curStk   = 0;

        // _elmts = new int[_numOfStk];
        _elmts = (int*) malloc(_numOfStk * sizeof(int));
        for(int i = 0; i < _numOfStk; i++)
                _elmts[i] = -1;  // all are empty


        _stacks = (int **) malloc(_numOfStk * sizeof(int *));
        for (int i = 0; i<_numOfStk; i++)
                _stacks[i] = (int *) malloc(_thOfStk * sizeof(int));
        cout << n << " stacks are created, windex 0,..., " << n-1 << endl;
        cout << " the threshold for each stack is " << t << " elements " << endl;
}

////////////////////////////////////////////////////////////
SetOfStacks::~SetOfStacks()
{
        free(_elmts);
        free(_stacks);
        cout << " stacks are deleted!" << endl;
}

////////////////////////////////////////////////////////////
bool SetOfStacks::isFull(int k)
{
        return (_elmts[k] == _thOfStk-1);
}

////////////////////////////////////////////////////////////
bool SetOfStacks::isFull()
{
        return isFull(_numOfStk-1);
}

////////////////////////////////////////////////////////////
bool SetOfStacks::isEmpty(int k)
{
        return (_elmts[k] == -1);
}

////////////////////////////////////////////////////////////
bool SetOfStacks::isEmpty()
{
        return isEmpty(0);
}

////////////////////////////////////////////////////////////
void SetOfStacks::push(int n)
{
        if (isFull())
        {
                cout << "stack overflow! cann't push " << n << " value! " << endl;
                return;
        }       
        if (_elmts[_curStk] == _thOfStk - 1)
                _curStk++;
        cout << "value " << n << " pushed on stack " << _curStk <<  endl;
        _elmts[_curStk]++;
        _stacks[_curStk][_elmts[_curStk]] = n;
}

////////////////////////////////////////////////////////////
int SetOfStacks::pop()
{
        if (isEmpty())
        {
                cout << "stack under flow! " << endl;
                return INT_MAX;
        }
        int i = _stacks[_curStk][_elmts[_curStk]];
        cout << "value " << i << " is popped from stack " << _curStk << endl;
        _elmts[_curStk]--;  
        if ((_elmts[_curStk] == -1) & (_curStk > 0))
                _curStk--;
        
        return i;
}

////////////////////////////////////////////////////////////
int SetOfStacks::pop(int k)
{
        if (isEmpty(k))
        {
                cout << "stack under flow!" << endl;
                return INT_MAX;
        }

        if ((k > _numOfStk-1) | (k < 0))
        {
                cout << " stack index is out of range! " << endl;
                return INT_MAX;
        }

        
        int i = _stacks[k][_elmts[k]];
        cout << "value " << i << " is popped from stack " << k << endl;
        _elmts[k]--;
        if ((_elmts[k] == -1) & (k > 0) & (k == _curStk))
                _curStk--;
        return i;
}

////////////////////////////////////////////////////////////

void SetOfStacks::printAll()
{
        cout << "print all the stacks:" << endl;
        for (int i = 0; i < _numOfStk; i++)
        {
                if (isEmpty(i))
                        cout << "stack " << i <<  " is empty " << endl;
                else
                {
                        for (int j = 0; j <= _elmts[i]  ; j++)
                                cout << _stacks[i][j] << " " ;
                        cout << endl;
                }
        }
}

////////////////////////////////////////////////////////////
void SetOfStacks::printK(int k)
{
        if (k > _numOfStk-1)
        {
                cout << "index is more than the stack size!" << endl;
                return;
        }

        if (k < 0)
        {
                cout << "index is less than the stack size!" << endl;
                return;
        }

        if (isEmpty(k))
                        {
                                cout << "stack " << k <<  " is empty " << endl;
                                return;
        }
                else
                {
                        for (int j = 0; j <= _elmts[k]  ; j++)
                                cout << _stacks[k][j] << " " ;
                        cout << endl;
                }
}

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

int _tmain(int argc, _TCHAR* argv[])
{
        int n = 2;
        int t = 3;
        SetOfStacks stacks(n,t);
        
        stacks.push(1);
        stacks.push(2);
         stacks.push(3);
        
        stacks.push(10);
        stacks.push(20);
        stacks.push(30);

        stacks.push(100);
        stacks.push(200);
        stacks.push(300);

        stacks.push(1000);
        stacks.push(2000);
        stacks.push(3000);
        stacks.push(3001);
        stacks.push(3002);       

        stacks.printK(0);
        stacks.printK(1);
        stacks.printK(2);
        stacks.printK(3);
        stacks.printK(4);

        stacks.printAll();

        stacks.pop();
        stacks.pop();
        stacks.pop(0);
        stacks.pop(0);
        stacks.pop(0);
        stacks.pop(2);
        stacks.printAll();
        return 0;
}
1 Comment

Design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.We design this class using array instead of linkedlist

9/2/2015

0 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

Design a stack which, in addition to push and pop, also has a function min which returns the minimum element? 
Push, pop and min should all operate in O(1) time.
We design this class using array instead of linkedlist
 
By: Hamed Kiani (Sep. 2, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;

class minStack{

private:
        int* _main_stk;      // main stack
        int* _aux_stk;       // aux. stack to keep elements in sorted
        int _cap;        // the maximum capacity of stack
        int _top;        // size of stack

public:
        minStack(int n);
        ~minStack();
        void push(int data);
        int pop();
        bool is_empty();
        bool is_full();
        void print_stk();
        void print_aux_stk();
        int getMin();
};

minStack::minStack(int n)
{
        _cap = n;
        _main_stk = new int[_cap];
        _aux_stk  = new int[_cap];
        _top = -1;       
        cout << " an object of minStack is created!" << endl;
}

minStack::~minStack()
{       
        delete[] _main_stk;
        delete[] _aux_stk;
        cout << " an object of minStack is deleted!" << endl;
}

bool minStack::is_empty()
{
        return (_top == -1);
}

bool minStack::is_full()
{
        return (_top == _cap-1);
}

void minStack::push(int data)
{
        if (is_full())
        {
                cout << "stack overflow!" << endl;
                return;
        }
        cout << " The element " << data << " is pushed on the stack!" << endl;
        // if the stack is empty or data is less than all elements in the aux. stack, just push it
        if ((_top == -1) || (data <= _aux_stk[_top]))
        {
                _top++;             
                _main_stk[_top] = data;
                _aux_stk[_top]  = data;             
                return;
        }

        // otherwise, push data on the main stack and duplicate the current min in the new position
        int temp = _aux_stk[_top];
        _top++;             
        _main_stk[_top] = data;     
        _aux_stk[_top] = temp;      
}

// pop operation: simply just _top--!
int minStack::pop()
{
        if (is_empty())
        {
                cout << "underflow!" << endl;
                return INT_MAX;
        }       
        _top--;
        cout << " The element " << _main_stk[_top+1] << " is popped from the stack!" << endl;
}

// return min value
int minStack::getMin()
{
        return _aux_stk[_top];
}

// print the main stack
void minStack::print_stk()
{
        if (is_empty())
        {
                cout << " nothing to print!" << endl;
                return;
        }
        for (int j = 0; j <= _top; j++)
                cout << _main_stk[j] << " " ;
        cout << endl;
}

// print the main stack
void minStack::print_aux_stk()
{
        if (is_empty())
        {
                cout << " nothing to print!" << endl;
                return;
        }
        for (int j = 0; j <= _top; j++)
                cout << _aux_stk[j] << " " ;
        cout << endl;
}

////////////////////////////////////////////////////////////

int _tmain(int argc, _TCHAR* argv[])
{
        minStack stack(10);

        stack.push(12);
        stack.push(3);
        stack.push(4);   
        stack.push(11);

        stack.push(12);
        cout << "the min value is : " << stack.getMin() << endl;
        stack.push(11);
        stack.push(41);
        cout << "the min value is : " << stack.getMin() << endl;
        stack.push(12);
        stack.push(1);
        stack.push(3);
        
        cout << "the min value is : " << stack.getMin() << endl;
        stack.print_stk();
        stack.print_aux_stk();

        cout << "the min value is : " << stack.getMin() << endl;
        stack.pop();
        stack.pop();
        stack.pop();
        cout << "the min value is : " << stack.getMin() << endl;
        stack.print_stk();
        stack.print_aux_stk();
        return 0;
}
0 Comments

A class of K Stacks in a single array! Efficient memory and run time.: c++

9/2/2015

3 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

A class of K Stacks in a single array! Efficient memory and run time. 
 
By: Hamed Kiani (Sep. 2, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;

class kStacks{

private:
        int *arr;    // an array of size n to save the values in stacks
        int *top;    // an array of size k to keep the index of top values of k stacks
        int *next;   // an array of size n to keep the next entry in stacks
        int n,k; // n: size of array, k: number of stacks
        int next_slot;   // the next free slot in the array 

public:
        kStacks(int k1, int n1);
        ~kStacks();         
        bool is_full() { return (next_slot == -1);}
        bool is_empty(int sn) { return(top[sn] == -1);}
        void push(int sn, int data);
        int pop(int sn);
        void print_sn(int sn);
};

// constructor
kStacks::kStacks(int k1, int n1)
{
        k = k1; n = n1; 
        arr  = new int[n];    // to keep the values in the stacks
        top  = new int[k];    // to keep the last index of stacks
        next = new int[n];    // to handle the next and previous index of stacks

        // initial to -1, all k stacks are empty
        for (int i = 0; i < k; i++)
                top[i] = -1;

        // the next slot of each entry is the next index
        for (int i = 0; i < n-1; i++)
                next[i] = i+1;

        // for the last entry there is no free slot
        next[n-1] = -1;
        // the initial free slot is arr[0]
        next_slot = 0;
}

// destructor
kStacks::~kStacks()
{
        k = 0; n = 0;
        delete[] arr;
        delete[] next; 
        delete[] top;
}
 
// push operator
void kStacks::push(int sn, int data)
{
        // wrong stack number
        if (sn > k-1)
        {
                cout << "sn must be in [0...k-1]" << endl;
                return;
        }

        // first check if the stack sn is overflow
        if (is_full())
        {
                cout << "stack overflow! cann't push!" << endl;
                return;
        }
        // keep the next free slot in i, we will use this to push data in arr
        int i = next_slot;
        // update the next free slot using next[i]. next free slot will be used for next push operation
        next_slot = next[i];
        // now we use next in a different role, to keep the second top value in stack, 
        next[i] = top[sn];
        // update the top by i
        top[sn] = i;
        // push the data in arr[i]
        arr[i] = data;
}

// pop operator
int kStacks::pop(int sn)
{
        if (sn > k-1)
        {
                cout << "sn must be in [0...k-1]" << endl;
                return INT_MAX;
        }
        if (is_empty(sn))
        {
                cout << "stack underflow! cann't pup!" << endl;
                return INT_MAX;
        }
        // keep the current index of stack sn
        int i = top[sn];
        // keep the previous index of stack sn in top
        top[sn] = next[i];
        // initialize the next[i] by next free slot
        next[i] = next_slot;
        // next free slot is current i
        next_slot = i;
        // return current value
        return arr[i];
}

// print the stack sn
void kStacks::print_sn(int sn)
{
        if (sn > k-1)
        {
                cout << "sn must be in [0...k-1]" << endl;
                return;
        }
        if (is_empty(sn))
        {
                cout << "no value to print" << endl;
                return;
        }

        int i = top[sn];
        
        while(next[i] != -1)
        {
                cout << arr[i] << " ";
                i =  next[i];
        }
        // for the last stack value with next[i] = -1;
        cout << arr[i] << endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
        kStacks stack(3, 10);
        stack.push(0, 1);
        stack.push(0, 2);
        stack.push(0, 3);

        stack.push(1, 10);
        stack.push(1, 20);

        stack.push(2, 100);
        stack.push(2, 200);

        stack.print_sn(0);

        stack.pop(0);
        stack.pop(0);
        stack.print_sn(0);
        
        stack.print_sn(1);
        stack.print_sn(2);
        return 0;
}
3 Comments

Stack class: c++ code: we assume that there is not stack overflow error!

9/1/2015

2 Comments

 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/******************************************************************************************
*******************************************************************************************
Chapter 3 Stack and Queue

A simple class of Stack!
 
By: Hamed Kiani (Sep. 1, 2015)
******************************************************************************************
******************************************************************************************/

#include "stdafx.h"
#include <iostream>
using namespace std;


struct Node{
        int _data;
        Node* _next;
};

class myStack{
private:
        Node* _head;
        int _size;

public:
        myStack();
        ~myStack(); 
        void push(int data);
        void pop();
        Node* return_top();
        int get_size();
        bool is_empty();
        void clear();
        void print_stack();
};

// constructor
myStack::myStack()
{
        _head = NULL;
        _size = 0;
}
myStack::~myStack()
{
        clear();
}

// is empty function
bool myStack::is_empty()
{
        return (_size == 0);
}

// retrun the stack size
int myStack::get_size()
{
        return _size;
}

// puch on the top
void myStack::push(int data)
{
        Node* temp = new Node;
        temp->_data = data;
        temp->_next = _head;
        _head = temp;
        _size++;
}

// pop the top data
void myStack::pop()
{
        if (is_empty())
        {
                cout << " the stack is empty, poping faild" << endl;
                return;
        }

        Node* temp  = _head;
        _head = _head->_next;
        delete temp;
        _size--;
}

// return the pointer of the top value
Node* myStack::return_top()
{
        if (is_empty())
                return NULL;
        Node* temp = _head;
        return temp;
}

// empty the stack
void myStack::clear()
{
        while(_size)
                pop();
        cout << " stack is deleted" << endl;
}

// print the stack values
void myStack::print_stack()
{
        Node* temp = _head;
        while(temp != NULL){
                cout << temp->_data << " " ;
                temp = temp->_next;
        }
        cout << endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
        myStack stack;  
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.print_stack();
        cout << stack.get_size() << endl;
        stack.pop();
        stack.print_stack();

        Node* temp = stack.return_top();
        cout << temp->_data << endl;

        return 0;
}
2 Comments
    A place to practice the coding interview.

    Author

    Hamed Kiani

    Categories

    All
    Arrays And Strings
    Linked List
    Stack And Queue
    Trees And Graphs

    Archives

    September 2015
    July 2015

    RSS Feed

Copyright © 2020, Hamed Kiani