티스토리 뷰

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
#ifndef LISTBASESTACK_H
#define LISTBASESTACK_H
 
typedef int LData;
 
class Node
{
private:
    LData data;
public:
    Node *next;
 
    Node(LData data):data(data){}
    LData getData(){return data;}
};
 
class ListStack
{
private:
    Node *head;
public:
 
    ListStack()
    {
        head = nullptr;
    }
 
    bool SIsEmpty();
    void SPush(LData data);
    LData SPop();
    LData SPeek();
};
#endif // LISTBASESTACK_H
cs




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
#include<iostream>
#include"ListBaseStack.h"
using namespace std;
 
bool ListStack::SIsEmpty()
{
    if (head == nullptr)
        return true;
    else
        return false;
}
 
void ListStack::SPush(LData data)
{
    Node *newNode = new Node(data);
 
    newNode->next = head;
    head = newNode;
}
 
LData ListStack::SPop()
{
    LData rdata;
    Node *rnode;
    
    if (SIsEmpty())
    {
        cout << "Stack is empty!" << endl;
        exit(-1);
    }
        
    rdata = head->getData();
    rnode = head;
    head = head->next;
    delete rnode;
    return rdata;
}
 
LData ListStack::SPeek()
{
    if (SIsEmpty())
    {
        cout << "Stack is empty!" << endl;
        exit(-1);
    }
 
    return head->getData();
}
 
int main()
{
    ListStack stack;
 
    stack.SPush(1);
    stack.SPush(2);
    stack.SPush(3);
    
    while (!stack.SIsEmpty())
        cout << stack.SPop() << " ";
 
    return 0;
}
cs


Comments