굿리치책으로 공부하는데 이중 링크드 리스트 공부하는데
책에 예제 없이 프로그램 코드만 나와 있어서 일단 헤더를 아래로 만들고 예제 cpp를 하니까 예제가 잘못되었는지 값들이 이상한 값 뜨는데 간단히 구현 예제 없을까
------------------------------------
#pragma once
#include <stdio.h>
#include <string>
#include <iostream>
using namespace::std;
typedef int Elem;
class NodeList {
private:
struct Node {
Elem elem;
Node *prev;
Node *next;
};
public:
class Iterator {
public:
Elem& operator*();
bool operator==(const Iterator& p) const {
return v == p.v;
}
bool operator!=(const Iterator& p) const {
return v != p.v;
}
Iterator& operator++() {
v = v->next;
return *this;
}
Iterator& operator--() {
v = v->prev;
return *this;
}
friend class NodeList;
private:
Node *v;
Iterator(Node *u);
};
public:
NodeList() {
n = 0;
header = new Node;
trailer = new Node;
header->next = trailer;
trailer->prev = header;
}
int size() const {
return n;
}
bool empty() const {
return (n == 0);
}
Iterator begin() const {
return Iterator(header->next);
}
Iterator end() const {
return Iterator(trailer);
}
void insertFront(const Elem& e) {
insert(begin(), e);
}
void insertBack(const Elem& e) {
insert(end(), e); //
}
void insert(const Iterator& p, const Elem& e) {
Node *w = p.v;
Node *u = w->prev;
Node *v = new Node;
v->elem - e;
v->next = w;
w->prev = v;
v->prev = u;
u->next = v;
n++; //노드 수 증가
}
void eraseFront() {
erase(begin());
}
void eraseBack() {
erase(--end());
}
void erase(const Iterator& p) {
Node *v = p.v;
Node *w = v->next;
Node *u = v->prev;
u->next = w;
w->prev = u;
delete v;
n--; //노드 수 감소
}
private:
int n;
Node *header;
Node *trailer;
};
NodeList::Iterator::Iterator(Node *u) { //private 안에 넣어도 되는지 몰라서 일단 빼봄
v = u;
}
Elem& NodeList::Iterator::operator*() {
return v->elem;
}
댓글 0