printf("ho_tari\n");

Linked List 본문

C++

Linked List

호타리 2023. 9. 5. 12:12

<main.cpp>

#include "list.h"

#include <iostream>

#include <cstdlib>



int main(void)

{

	List list;

	

	//insertFirstNode(&list, 4);     // [4]

	list.insertFirstNode(4);

	list.printList();

	//insertFirstNode(&list, 3);     // [3, 4]

	list.insertFirstNode(3);

	list.printList();

	//insertFirstNode(&list, 1);     // [1, 3, 4]

	list.insertFirstNode(1);

	list.printList();

	

	//insertNode(&list, 1, 2);     // [1, 2, 3, 4]

	list.insertNode(1, 2);

	list.printList();

	

	//deleteNode(&list, 3);        // [1, 2, 4]

	list.deleteNode(3);

	list.printList();

	

	//cleanupList(&list);

	

	return 0;

}

 

<list.h>

#pragma once



struct Node {

	int data;

	struct Node* next;

	Node(int data, Node* next);

	~Node();

};



struct List {

private:

	struct Node* ptr;

public:

	List();

	~List();

	void printList();

	void insertFirstNode(int data); // 첫번째 노드에 데이터 추가

	void insertNode(int prevData, int data); // prevdata 뒤의 노드에 데이터 추가

	void deleteNode(int data);  // 데이터 삭제

};

 

<list.cpp>

#include "list.h"

#include <cstdlib>

#include <iostream>



Node::Node(int data, Node* next) {

	this->data = data;

	this->next = next;

}

Node::~Node() {



}



List::List()

{

	Node* p = new Node(-1, nullptr);

	this->ptr = p; // 더미노드에는 아무값이 들어와도 상관x

}



List::~List()

{

	Node* ptr = this->ptr;

	while (ptr) {

		Node* tmp = ptr;

		ptr = ptr->next;

		delete tmp;

	}

}

void List::printList()

{

	Node* ptr = this->ptr->next;

	std::cout << "[";

	while (ptr) {

		std::cout << ptr->data;

		if (ptr->next != nullptr) {

			std::cout << ", ";

		}

		else {

			std::cout << "";

		}

		ptr = ptr->next;

	}

	std::cout<< "]" << std::endl;

}



void List::insertFirstNode(int data)

{

	this->ptr->next = new Node(data, this->ptr->next);

}



void List::insertNode(int prevData, int data)

{

	Node* ptr = this->ptr->next;

	while (ptr) {

		if (ptr->data == prevData) {

			break;

		}

		ptr = ptr->next;

	}

	if (ptr) {

		ptr->next = new Node(data, ptr->next);

	}

}



void List::deleteNode(int data)

{

	Node* ptr = this->ptr->next;

	Node* ptr2 = this->ptr; // ptr뒤에서 따라가는 node

	while (ptr) {

		if (ptr->data == data) {

			break;

		}

		ptr = ptr->next;

		ptr2 = ptr2->next;

	}

	if (ptr) {

		ptr2->next = ptr->next;

		delete ptr;

	}

}

 

<compile 결과>

'C++' 카테고리의 다른 글

Stack2 (extern, explicit)  (0) 2023.09.07
Array (array 클래스)  (0) 2023.09.07
String (클래스 개선)  (0) 2023.09.05
StringRep (reference counting 참조 계수)  (0) 2023.09.05
Complex (istream 입력 함수)  (0) 2023.09.05