21.12.2011, 13:54. Просмотров 763. Ответов 5
задача - реализовать стек через класс, все основные функции со стеком, и самое главное, рекурсивную функцию, которая выводит стек в обратном порядке.
st.h
C++ |
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
| #ifndef ST_H_
#define ST_H_
class Stack
{
public:
Stack();
~Stack();
void push(void *data);
void *pop();
void print();
void recurc();
private:
typedef struct Element {
struct Element *next;
void *data;
} Element;
Element *top;
};
#endif |
|
function_stek.cpp
C++ |
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
| #include <iostream>
#include "st.h"
using namespace std;
Stack::Stack() {
top = NULL;
}
Stack::~Stack() {
while(top) {
Element *elm = top->next;
delete top;
top = elm;
}
}
void Stack::push(void *data) {
Element *elm = new Element;
elm->data = data;
elm->next = top;
top = elm;
}
void *Stack::pop() {
void *data;
if(top == NULL) return data;
data = top->data;
Element *elm = top;
top = elm->next;
delete elm;
return data;
}
void Stack::print() {
Element *elm = top;
while(elm) {
cout << *(static_cast<int*>(elm->data)) << " " ;
elm = elm->next;
}
cout << endl;
}
void Stack::recurc()
{
if( ){
recurc( );
cout << *(static_cast<int *>(top->data)) << " ";
}
cout << endl;
} |
|
main.cpp
C++ |
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
| #include <iostream>
#include "st.h"
using namespace std;
int main()
{
Stack *st = new Stack;
int n1 = 10;
int n2 = 20;
int n3 = 30;
int n4 = 40;
int n5 = 50;
st->push(&n1);
st->push(&n2);
st->push(&n3);
st->push(&n4);
st->push(&n5);
st->print();
cout << *(static_cast<int*>(st->pop()))<< " poped\n";
cout << *(static_cast<int*>(st->pop()))<< " poped\n";
cout << "Print stack ";
st->print();
cout << "Recurc ";
st->recurc();
cout << endl;
} |
|
Понимаю, что рекурсивную функцию надо делать с аргументами, тогда получается, что всё в .h надо в паблик? Или как ее сделать?
Спасибо