|자료구조| 1 | Circular LinkedList_2 | 원형 연결 리스트
컴퓨터/자료구조

|자료구조| 1 | Circular LinkedList_2 | 원형 연결 리스트

no title

원형 연결 리스트 구현

Visual Studio 솔루션 구성


구현부

노드 - 헤더 : Node.h

#pragma once
#include "CircuitLinkedList.h"
class Node
{
    friend class CircuitLinkedList;
protected :
	int data;
	Node* next;
};

원형 연결 리스트 - 헤더 : CircuitLinkedList.h

#pragma once
#include "Node.h"
class CircuitLinkedList
{
	friend class Node;
private :
	//멤버변수
	Node* tail;
	int length;
public :
	//매서드
	CircuitLinkedList();
	void LInsert(int data);
	int LDel();
	int LStatus();
};

//이곳은 그냥 클래스의 구성요소만 적기를 바란다

원형 연결 리스트 - 메소드 : CircuitLinkedList.cpp

#include "CircuitLinkedList.h"
#include "Node.h"
#include <iostream>
#include <algorithm>
using namespace std;

CircuitLinkedList::CircuitLinkedList() {
	this->tail = NULL;
	this->length = 0;
}

void CircuitLinkedList::LInsert(int _data) {
	Node* newNode = new Node;
	newNode->data = _data;

	//리스트가 하나도 없었을때
	if (this->tail == NULL) {
		this->tail = newNode;
		//원형리스트라서 자기자긴을 붙여야함
		newNode->next = newNode;
	}
	else {
		//마지막을 찾아갈때 while 쓸필요가 없는게 어차핀 tail이 마지막을 보장한다
		//while (this->tail != NULL) {}

		//this->tail은 마지막 노드 그 자체
			//그래서 마지막노드 넥스트를 사용할 수 있다.
				//그렇다면 아까부터 head가 없었는데 head는 어떻게 지목하지?
				//tail->next는 바로 head를 가르키는것이다.
		newNode->next = this->tail->next;
		this->tail->next = newNode;
		this->tail = newNode;
	}
	(this->length)++;
}

int CircuitLinkedList::LDel() {
	//tail 삭제
	if (this->length == 0)
		throw out_of_range("CircuitLinkedList 노드가 없습니다");
	//rpos는 기존 tail이 삭제되고
		//새로운 tail이 생기고 나서의 다음 head(tail->next)
	Node* rpos = this->tail->next;
	int result = this->tail->data;
	//arr의 다음은 tail 
		//tail이 사라지면 다음 tail의 후보가 된다
	Node* arr = this->tail->next;
	while (1) {
		if (arr->next == this->tail)
			break;
		else
			arr = arr->next;
	}
	delete this->tail;
	this->tail = arr;
	this->tail->next = rpos;
	this->length--;
	return result;
}

int CircuitLinkedList::LStatus() {
	cout << "현재 개수 : " << this->length << endl;

	if (this->length == 0) return 0;

	cout << "처음 ::  " << this->tail->next->data << endl;
	cout << "끝 :: " << this->tail->data << endl;

	Node* arr = this->tail->next;
	for (; this->tail != arr;)
	{
		cout << arr->data << " ";
		arr = arr->next;
	}

	// for문에서 출력 되지 못하는 마지막 값 출력
	cout << arr->data << endl;
	return 1;
}

//헤더파일을 include 하자
//여기는 클래스 매서드 구현부를 적는다

적용부

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

void _Interface_(CircuitLinkedList *_plist) {
	while (1) {
		cout << "1.삽입 " << "2.삭제 " << "3.출력 " << "4.종료 " << '\n';
		int num; cin >> num;
		if (num == 1) {
			int inputNum; cin >> inputNum;
			_plist->LInsert(inputNum);
		}
		else if (num == 2) {
			cout << _plist->LDel() << '\n';
		}
		else if (num == 3) {
			_plist->LStatus();
		}
		else if (num == 4) {
			break;
		}
	}
}

int main() {
	CircuitLinkedList Clist;
	_Interface_(&Clist);
}

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