Algorithm
링크드 리스트
일등하이
2021. 3. 19. 17:49
반응형
ko.wikipedia.org/wiki/%EC%97%B0%EA%B2%B0_%EB%A6%AC%EC%8A%A4%ED%8A%B8
연결 리스트 - 위키백과, 우리 모두의 백과사전
위키백과, 우리 모두의 백과사전.
ko.wikipedia.org
using System;
using System.Collections.Generic;
namespace Study06
{
public class App
{
LinkedList list = new LinkedList();
LinkedList.Node head = null;
//생성자
public App()
{
list.AppendNode(ref head, list.CreateNode(10));
list.InsertAfter(head, list.CreateNode(20));
Print();
Console.WriteLine("2번째 노드 뒤에 노드 추가");
var current = list.GetNodeAt(head, 2);
var newNode = list.CreateNode(3000);
list.InsertAfter(current, newNode);
Print();
int count = list.GetNodeCount(head);
Console.WriteLine("모든 노드 제거");
//모든 노드 제거
for (int i = 0; i < count; i++)
{
var target = list.GetNodeAt(head, 0);
if (target != null)
{
list.Remove(ref head, target);
list.DestoryNode(target);
}
}
count = list.GetNodeCount(head);
Console.WriteLine("count: {0}", count);
}
private void Print()
{
int count = list.GetNodeCount(head);
//리스트 출력
for (int i = 0; i < count; i++)
{
var node = list.GetNodeAt(head, i);
Console.WriteLine(node.data);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study06
{
public class LinkedList
{
public class Node
{
public int data;
public Node nextNode;
//생성자
public Node(int data) {
this.data = data;
}
}
//생성자
public LinkedList() {
}
//노드 생성
public Node CreateNode(int data) {
return new Node(data);
}
//노드 소멸
public void DestoryNode(Node node) {
node = null;
}
//노드 추가
public void AppendNode(ref Node head, Node newNode) {
if (head == null)
{
head = newNode;
}
else
{
Node tail = head;
while (tail.nextNode != null) {
tail = tail.nextNode;
}
tail.nextNode = newNode;
}
}
//노드 삽입
public void InsertAfter(Node current, Node newNode) {
newNode.nextNode = current.nextNode;
current.nextNode = newNode;
}
//노드 제거
public void Remove(ref Node head, Node remove) {
if (head == remove)
{
head = remove.nextNode;
}
else
{
Node current = head;
while (current != null && current.nextNode != remove) {
current = current.nextNode;
}
if (current != null) {
current.nextNode = remove.nextNode;
}
}
}
//노드 탐색
public Node GetNodeAt(Node head, int location) {
Node current = head;
while (current != null && (--location) >= 0) {
if (current.nextNode == null)
{
return current;
}
else
{
current = current.nextNode;
}
}
return current;
}
//노드의 수
public int GetNodeCount(Node head) {
int count = 0;
Node current = head;
while (current != null) {
current = current.nextNode;
count++;
}
return count;
}
}
}
반응형