알고리즘/DataStructure
[C++] 자료구조/LinkedList 구현
Jay, Lee
2021. 8. 28. 15:14
int형 LinkedList
데이터 타입은 바꾸거나
typedef로 지정을 해주거나 할 수 있다.
중간에 데이터를 넣는 것은 구현하지 않았다.
#include <iostream>
#include <string>
using namespace std;
class intNode {
private:
int dat;
intNode* next;
intNode(int x) {
this->dat = x;
this->next = NULL;
}
friend class intLinkedList;
};
class intLinkedList {
private:
intNode* head;
intNode* tail;
public:
intLinkedList()
:head(NULL), tail(NULL) {
}
~intLinkedList() {}
void addFront(int x) {
intNode* n = new intNode(x);
if (empty()) {
head = n;
tail = n;
}
else {
n->dat = x;
n->next = head;
head = n;
}
}
void removeFront() {
if (empty()) {
cout << -1 << "\n";
}
else {
intNode* old = head;
head = old->next;
cout << old->dat << "\n";
delete old;
if (head == NULL) {
tail = NULL;
}
}
}
void front() {
if (empty()) {
cout << -1 << "\n";
}
else {
cout << head->dat << "\n";
}
}
int empty() {
if (head == NULL && tail == NULL) {
return 1;
}
else {
return 0;
}
}
void showList() {
if (empty()) {
cout << -1 << "\n";
}
else {
intNode* n = head;
while (n != tail) {
cout << n->dat << " ";
n = n->next;
}
cout << tail->dat << "\n";
}
}
void addBack(int x) {
intNode* n = new intNode(x);
if (empty()) {
head = n;
tail = n;
}
else {
tail->next = n;
tail = n;
}
}
};