|자료구조| 1 | Double LinkedList_3 | 이중 연결 리스트
컴퓨터/자료구조

|자료구조| 1 | Double LinkedList_3 | 이중 연결 리스트

no title

양방향 연결 리스트 구현

Visual Studio 솔루션 구성


구현부

노드 - 헤더 : Node.h

#pragma once
class Node
{
	friend class D_List;
protected:
	int data;
	Node* next;
	Node* prev;
};

양방향 연결 리스트 - 헤더 : D_List.h

#pragma once
#include"Node.h"
class D_List
{
	friend class Node;
private:
	Node* mHead;
	Node* mTail;
	Node* mCur;
	int mLength = 0;

public:
	D_List();
	int length();
	void insert(int);
	int front();
	int back();
	void pop_front();
	void pop_back();
	void list_state();
};

양방향 연결 리스트 - 메소드 : D_List.cpp

#include "D_List.h"
#include "Node.h"
#include <iostream>
#include <algorithm>

using namespace std;

D_List::D_List() {
	mHead = NULL;
	mTail = NULL;
	mCur = NULL;
	mLength = 0;
}

int  D_List::length() {
	return mLength;
};
void D_List::insert(int _data) {
    //일단 데이터 넣기
	Node* newNode = new Node;
	newNode->data = _data;

	if (mHead == NULL) {
        //처음 생성한것이라면?
		mHead = newNode;
		mTail = newNode;
		mHead->prev = NULL;
		mTail->next = NULL;
	}
	else {  
        //리스트가 만들어져 있다면?
		mTail->next = newNode;
		newNode->prev = mTail;
		mTail= newNode;
		newNode->next = NULL;
	}
	mLength++;
};
int  D_List::front() {
	return mHead->data;
};
int  D_List::back() {
	return mTail->data;
};
void  D_List::pop_front() {
	mCur = mHead;
	if (mCur == NULL)
		throw "Empty List";
	if (mCur->next != NULL) {
        //우측에 리스트가 있다면..
		mCur->next->prev = NULL;
		mHead = mCur->next;
		delete mCur;
	}
	else {
        //지금 리스트에 단 하나의 값밖에 없으면..
		mHead = NULL;
		mTail = NULL;
		delete mCur;
	}

	mLength--;
};
void  D_List::pop_back() {
	mCur = mTail;
	if (mCur == NULL)
		throw "Empty List";
	if (mCur->prev != NULL) {
		mCur->prev->next = NULL;
		mTail = mCur->prev;
		delete mCur;
	}
	else {
		mHead = NULL;
		mTail = NULL;
		delete mCur;
	}

	mLength--;
};
void D_List::list_state() {
	return;
};

적용부

main.cpp

#include "Class.h"
#include "D_List.h"
#include <iostream>
#include <algorithm>
using namespace std;

void _Interface_(D_List *_list) {
	while (1) {
		cout << "1 : 삽입 " << "2 : 삭제 앞" << "3 : 삭제 뒤" << "4. 앞" << "5. 뒤" << '\n';
		int num; cin >> num;
		if (num == 1) {
			int inputNum; cin >> inputNum;
			_list->insert(inputNum);
			cout << _list->length() << '\n';
		}
		else if (num == 2) {

			cout << _list->front() << '\n';
			_list->pop_front();
			cout << _list->length() << '\n';
		}
		else if (num == 3) {

			cout << _list->back() << '\n';
			_list->pop_back();
			cout << _list->length() << '\n';
		}
		else if (num == 4) {
			cout << _list->front() << '\n';
		}
		else if (num == 5) {
			cout << _list->back() << '\n';
		}
	}
}

int main() {
	D_List doubleList;
	_Interface_(&doubleList);
}

//클래스 헤더파일을 사용하자
//클래스를 사용할 메인 부분이다