-
이중 연결 리스트 (DoubleLinkedList)언어/C, C++ 2021. 1. 5. 14:47
#pragma once #include <iostream> using namespace std; struct Node { int data; Node* prev; // Previous 이전 Node* next; }; class DoubleLinkedList { private: int m_count; Node* m_head; Node* m_tail; public: DoubleLinkedList(); ~DoubleLinkedList(); void InsertToHead(int _item); void InsertToTail(int _item); void Delete(int _position); int Retrieve(int _position); bool IsEmpty(); int GetLength(); };
DoubleLinkedList.h
#include "DoubleLinkedList.h" DoubleLinkedList::DoubleLinkedList() :m_count(0), m_head(nullptr), m_tail(nullptr) { } DoubleLinkedList::~DoubleLinkedList() { } void DoubleLinkedList::InsertToHead(int _item) { Node* temp = new Node; temp->data = _item; if (m_count == 0) m_head = m_tail = temp; else { temp->next = m_head; m_head->prev = temp; m_head = temp; } m_count++; } void DoubleLinkedList::InsertToTail(int _item) { Node* temp = new Node; temp->data = _item; if (m_count == 0) m_head = m_tail = temp; else { temp->prev = m_tail; m_tail->next = temp; m_tail = temp; } m_count++; } void DoubleLinkedList::Delete(int _position) { Node* deleteNode; Node* currentNode = m_head; for (int i = 0; i < _position - 1; i++) m_head = m_head->next; if (_position == 1) { if (m_count > 1) { deleteNode = m_head; m_head = m_head->next; delete deleteNode; } else { deleteNode = m_head; m_head = m_tail = nullptr; delete deleteNode; } m_count--; } else if (_position == m_count) { deleteNode = m_head; m_head = m_head->prev; m_tail = m_head; delete deleteNode; m_head = currentNode; m_count--; } else { m_head->prev->next = m_head->next; m_head->next->prev = m_head->prev; deleteNode = m_head; delete deleteNode; m_head = currentNode; m_count--; } } int DoubleLinkedList::Retrieve(int _position) { Node* temp = m_head; for (int i = 0; i < _position - 1; i++) m_head = m_head->next; int tempNum = m_head->data; m_head = temp; return tempNum; } bool DoubleLinkedList::IsEmpty() { return m_count == 0; } int DoubleLinkedList::GetLength() { return m_count; }
DoubleLinkedList.cpp
'언어 > C, C++' 카테고리의 다른 글
연결 리스트 스택 (Linked List Stack) (0) 2021.01.13 배열 스택 (Array Stack) (0) 2021.01.12 연결 리스트 (Linked List) (0) 2020.12.31 배열 리스트 (Array List) (0) 2020.12.29 로또(Lotto) 프로그램 (0) 2020.08.20