Circular Linked List
2022. 5. 7. 02:58ㆍC++/자료구조
Circular Linked List
함수
- void Add(int value) : value를 LinkedList에 삽입한다.
- void Delete(int value) : 해당 value를 delete한다.
- bool IsExist(int value) : 해당 value가 있는지 확인한다.
- bool IsEmpty() : LinkedList가 비었는가?
- void ShowLinkedList() : LinkedList를 출력한다.
//main
#include "CircularLinkedList.h"
int main(void)
{
CircularLinkedList c1;
c1.Add(1);
c1.ShowLinkedList();
c1.Add(20);
c1.ShowLinkedList();
c1.Add(30);
c1.ShowLinkedList();
c1.DeleteValue(20);
c1.ShowLinkedList();
c1.DeleteValue(70);
c1.ShowLinkedList();
return 0;
}
//CircularLinkedList.h
#pragma once
struct Node
{
int Value;
Node* Next;
};
class CircularLinkedList
{
public:
CircularLinkedList();
~CircularLinkedList();
void Add(int value);
void DeleteValue(int value);
bool IsExist(int value);
bool IsEmpty();
void ShowLinkedList();
private:
Node* Tail;
};
//CircularLinkedList.cpp
#include "CircularLinkedList.h"
#include <iostream>
CircularLinkedList::CircularLinkedList():Tail(nullptr)
{
}
CircularLinkedList::~CircularLinkedList()
{
while (IsEmpty())
{
Node* Point = Tail;
Point->Next = Point->Next->Next;
delete Point->Next;
}
}
void CircularLinkedList::Add(int value)
{
if(IsEmpty())
{
Tail = new Node;
Tail->Next = Tail;
}
else
{
Node* NewTail = new Node;
NewTail->Next = Tail->Next;
Tail->Next = NewTail;
Tail = NewTail;
}
Tail->Value = value;
}
void CircularLinkedList::DeleteValue(int value)
{
if (IsEmpty())
{
std::cout << "Linked List is empty" << std::endl;
}
else if (IsExist(value))
{
if (Tail->Next == Tail)
{
delete Tail;
Tail = nullptr;
}
Node* PrePoint = Tail;
do
{
if (PrePoint->Next->Value == value)
{
break;
}
PrePoint = PrePoint->Next;
} while (PrePoint != Tail);
Node* Point = PrePoint->Next;
PrePoint->Next = Point->Next;
Point->Next = nullptr;
delete Point;
}
else
{
std::cout << "Linked List have not "<<value << std::endl;
}
}
bool CircularLinkedList::IsExist(int value)
{
if (IsEmpty())
{
return false;
}
Node* Point = Tail->Next;
while (Point != Tail)
{
if (Point->Value == value)
{
return true;
}
Point = Point->Next;
}
return false;
}
bool CircularLinkedList::IsEmpty()
{
return (Tail == nullptr);
}
void CircularLinkedList::ShowLinkedList()
{
Node* Point = Tail->Next;
while (Point != Tail)
{
std::cout << " -> " << Point->Value;
Point = Point->Next;
}
std::cout << " -> " << Point->Value <<std::endl;
}
'C++ > 자료구조' 카테고리의 다른 글
Singly Linked List (0) | 2022.05.07 |
---|---|
이중연결리스트 (0) | 2022.04.30 |
배열을 이용한 큐 구현 (0) | 2022.04.29 |
배열을 이용한 원형 큐의 확장 (0) | 2022.04.29 |
스택: 배열의 확장 (0) | 2022.04.27 |