2008. 5. 9. 22:24ㆍETC Programmings
C#으로 구현한 LinkedList 여전히 null 값에 대한 의문이 남는다. Nullable을 구현해 줘야 되는거 같기는 한데, 제너릭에 자바에서 처럼 extends 라는 키워드 대신에 where 라는 키워드를 사용한다고 하는데 아직까지는 잘 모르겠다. 때문에 null 값으로 지정하지 않고 구현해봐따. ㅋ
using System;
using System.Collections.Generic;
using System.Text;
namespace List
{
public class LinkedList<T> : ListInterface<T>
{
private Node firstNode;
private int length;
public LinkedList()
{
reset();
}
public void add(T entry)
{
if (length == 0)
firstNode = new Node(entry);
else
getNodeAt(length - 1).nextNode = new Node(entry);
length++;
}
private Node getNodeAt(int position)
{
Node currentNode = firstNode;
for (int i = 0; i < position; i++)
currentNode = currentNode.nextNode;
return currentNode;
}
public void add(T entry, int index)
{
if (index >= length)
add(entry);
else
{
Node previousNode = getNodeAt(index - 1);
Node nextNode = getNodeAt(index);
previousNode.nextNode = new Node(entry, nextNode);
}
length++;
}
public void remove(int index)
{
// 원래 있던 노드는 어떻게 null 값으로 만드냐 ㅠㅠ
getNodeAt(index - 1).nextNode = getNodeAt(index + 1);
length--;
}
public void replace(T newEntry, int index)
{
getNodeAt(index).data = newEntry;
}
public T get(int index) {
return getNodeAt(index).data;
}
public bool isContains(T entry) {
for (int i = 0; i < length; i++)
if (getNodeAt(i).data.Equals(entry))
return true;
return false;
}
public void reset()
{
firstNode = null;
length = 0;
}
public bool isFull()
{
Console.WriteLine("이 메소드는 지원하지 않습니다");
return false;
}
public bool isEmpty()
{
return firstNode == null && length == 0;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
sb.Append("[" + get(i).ToString() + "] ");
return sb.ToString();
}
public class Node
{
public T data;
public Node nextNode;
public Node(T data)
{
this.data = data;
this.nextNode = null;
}
public Node(T data, Node nextNode)
{
this.data = data;
this.nextNode = nextNode;
}
}
}
}
private Node getNodeAt(int position)
{
Node currentNode = firstNode;
for (int i = 0; i < position; i++)
currentNode = currentNode.nextNode;
return currentNode;
}
요거 하나는 정말 잘만들었다 +_+ ㅋㅋㅋㅋ 여러 메소드들에서 요긴하게 쓰이는 착한 메소드-