Notice
Recent Posts
Recent Comments
Link
스토리지
[3.30] Queue 연습 2 (링크드리스트) 본문
using System;
namespace Study01
{
public class Node<T>
{
public T data;
public Node<T> next;
public Node(T data)
{
this.data = data;
}
}
public class Queue<T>
{
private Node<T> head;
private Node<T> tail;
public Queue()
{
head = tail = null;
}
public void Enqueue(T data)
{
if(head == null)
{
head = new Node<T>(data);
tail = head;
return;
}
tail.next = new Node<T>(data);
tail = tail.next;
}
public T Dequeue()
{
T returnData = default(T);
if(head == null)
{
throw new NullReferenceException("Queue is empty.");
}
returnData = head.data;
head = head.next;
if(head == tail)
{
head = tail = null;
}
return returnData;
}
public override string ToString()
{
string result = string.Empty;
for(Node<T> i = head; i != null; i = i.next)
{
result += string.Format("{0} ", i.data);
}
return result;
}
}
}
using System;
namespace Study01
{
public class App
{
public App()
{
Queue<char> queue = new Queue<char>();
string tmp = "Hello World!";
char[] helloWorld = tmp.ToCharArray();
for(int i = 0; i < helloWorld.Length; i++)
{
queue.Enqueue(helloWorld[i]);
}
Console.Write("원래 데이터 출력 : ");
Console.WriteLine(queue);
queue.Dequeue();
queue.Dequeue();
queue.Dequeue();
queue.Dequeue();
Console.Write("Dequeue(4) 연산 이후 데이터 출력 : ");
Console.WriteLine(queue);
}
}
}
- 제너릭으로 만듬으로서 모든 자료형을 받을 수 있음.
- ToString 메서드의 오버라이딩으로 객체 이름만으로 큐 내용을 출력할 수 있게 만듬.
- 배열로 만드는 거 보다 확실히 연결리스트로 만드는 것이 훨씬 편하다.
'Unity > 자료구조' 카테고리의 다른 글
[3.30] Tree (일반적인 트리) (0) | 2021.03.30 |
---|---|
[3.30] Stack (0) | 2021.03.30 |
[3.30] Queue 연습 1 (원형배열) (0) | 2021.03.30 |
[3.30] Queue (0) | 2021.03.30 |
[3.30] Single Linked List 복습 (0) | 2021.03.30 |
Comments