Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- C++
- 프로그래밍
- 자바
- backend
- SNS
- java정리
- 풀스택프레임워크
- java
- 빅데이터
- 프로그래머스
- 코테
- 백준
- 이웃한 칸
- 모의 주식
- 코스닥
- 개인프로젝트
- 프로그램
- Python
- 자바정리
- 자바독학
- 코딩독학
- 개발자
- frontend
- 개발
- 주가예측
- 코딩
- 사물인터넷
- 코딩테스트
- Reflex
- Project
Archives
- Today
- Total
Creative Code
main.cpp(linked list) 본문
※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 |