Creative Code

main.cpp(linked list) 본문

C++ Programming

main.cpp(linked list)

빛하루 2023. 8. 29. 23:05

※main.cpp파일

#include <iostream>
#include <cstdlib>
#include "list.h"

int main(void)
{
	List list;
	list.insertFirstNode(4); //[4]
	list.printList();
	list.insertFirstNode(3); //[3,4]
	list.printList();
	list.insertFirstNode(1); //[1,3,4]
	list.printList();
	list.insertNode(1, 2);  //[1,2,3,4]
	list.printList();
	list.deleteNode(3); 		//[1,2,4]
	list.printList();
	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;
	}
}

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

main.cpp(Rational 사칙연산)  (0) 2023.08.30
main.cpp(complex 연산)  (0) 2023.08.30
main.cpp(complex 클래스)  (0) 2023.08.30
main.cpp(queue)  (0) 2023.08.29
main.cpp(스택)  (0) 2023.08.29