Creative Code

list2(linked list 클래스 연결) 본문

C++ Programming

list2(linked list 클래스 연결)

빛하루 2023. 9. 5. 14:42

※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