Stack
- Linked list 를 만든 김에 Stack도 구현했다.
- push와 pop의 메소드만 잘 정의해주면 된다.
- queue까지만 만들고 다른거 공부해야지 간만에 하니까 재밌다.
#include <iostream>
using namespace std;
class Node
{
Node * nextN;
int key;
public:
Node(){}
Node(int key): key(key) {}
void setNext(Node * n){
nextN = n;
}
Node* getNext(){
return nextN;
}
int getKey(){
return key;
}
};
class Stack
{
private:
Node* head;
Node* tail;
public:
Stack(){
head = new Node();
tail = new Node();
head->setNext(tail);
tail->setNext(head);
}
~Stack(){
clear();
delete head;
delete tail;
}
void push(int key){ // in
Node* temp = new Node(key);
temp->setNext(head->getNext());
head->setNext(temp);
}
int pop(){ // out
Node* temp = head->getNext();
head->setNext(temp->getNext());
int ret = temp->getKey();
delete temp;
return ret;
}
void showList(){ // stack 출력
Node* temp = head->getNext();
while(temp != tail){
cout<<temp->getKey()<<" ";
temp = temp->getNext();
}
cout<<endl;
}
void clear(){ // 전체 pop
Node* temp = head->getNext();
while(temp != tail){
Node* del = temp;
temp = temp->getNext();
delete del;
}
head->setNext(tail);
}
};
int main(){
Stack s = Stack();
s.push(10);
s.push(20);
s.showList();
s.push(22);
s.showList();
s.pop();
s.showList();
s.clear();
s.showList();
return 0;
}