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
- 빅데이터
- 주가예측
- 자바독학
- java
- Python
- 코테
- backend
- 코딩테스트
- 개발자
- 풀스택프레임워크
- Reflex
- 개인프로젝트
- Project
- C++
- 개발
- 이웃한 칸
- java정리
- 자바정리
- 코딩
- 백준
- 자바
- 사물인터넷
- 프로그램
- 코딩독학
- SNS
- 프로그래머스
- 모의 주식
- 프로그래밍
- 코스닥
- frontend
Archives
- Today
- Total
Creative Code
list2(linked list 클래스 연결) 본문
※main.cpp파일
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main(void)
{
List list;
//initList();
list.insertFirstNode(4); //[4]
std::cout <<list << std::endl;
list.insertFirstNode(3); //[3,4]
std::cout <<list << std::endl;
list.insertFirstNode(1); //[1,3,4]
std::cout <<list <<std::endl;
list.insertNode(1, 2); //[1,2,3,4]
std::cout << list << std::endl;
list.deleteNode(3); //[1,2,4]
std::cout << list <<std::endl;
//list.cleanupList();
return 0;
}
※list.h 파일
#ifndef LIST_H
#define LIST_H
#include <iostream>
class Node {
friend class List;
private:
int data;
Node *next;
Node(int data, Node *next);
};
class List {
friend std::ostream& operator << (std::ostream& out, const List &rhs);
private:
Node *ptr;
List(const List& rhs);
List& operator=(const List&rhs);
public:
List();
~List();
std::ostream& printList(std::ostream& out) const;
void insertFirstNode(int data); // 첫번째 노드에 데이터 추가
void insertNode(int prevData, int data); // prevdata 뒤의 노드에 데이터 추가
void deleteNode( int data); // 데이터 삭제
};
#endif
※list.cpp파일
#include "list.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
std::ostream& operator<<(std::ostream& out,const List& rhs) {
return rhs.printList(out);
}
Node::Node(int data, Node *next) {
this->data = data;
this->next = next;
}
List::List() {
//this->ptr = createNode(-1,NULL);
this->ptr = new Node(-1,NULL);
}
List::~List() {
Node *ptr = this->ptr;
while (ptr){
Node *tmp = ptr;
ptr = ptr->next;
delete tmp;
}
}
std::ostream& List::printList(std::ostream& out) const
{
Node *ptr = this->ptr->next;
out <<'[';
while (ptr) {
out << (ptr->data) << ((ptr->next) ? ", " : "");
ptr = ptr->next;
}
out << ']';
return out;
}
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;
while (ptr){
if (ptr->data == data){
break;
}
ptr = ptr->next;
ptr2 = ptr2 ->next;
}
if (ptr){
ptr2->next = ptr->next;
delete ptr;
}
}
'C++ Programming' 카테고리의 다른 글
stack2(extern,explicit사용) (0) | 2023.09.06 |
---|---|
array(array 클래스) (0) | 2023.09.05 |
string4(reference counting사용) (0) | 2023.09.05 |
string3(string 클래스 개선) (0) | 2023.09.05 |
add.cpp(cin으로 입력받기) (0) | 2023.09.05 |