C#

04/06 단일연결리스트 Add구현 및 인덱서 사용 연습

박준희 2021. 4. 6. 00:41
728x90

 

Program.cs

namespace Study07
{
    class Program
    {
        static void Main(string[] args)
        {
            new App();
        }
    }
}

 

App.cs

using System;
using System.Threading;

namespace Study07
{
    public class App
    {       
        public App()
        {
            SingleLinkedList list = new SingleLinkedList();
            list.Add(new Node("A"));
            list.Add(new Node("B"));
            list.Add(new Node("C"));
            list.Add(new Node("D"));

            Console.WriteLine("단일연결리스트 3번째 요소 :" + list[2].data);
            Console.WriteLine("3번째 요소의 데이터 변경 C -> G");
            list[2].data = "G";
            Console.WriteLine("단일연결리스트 3번째 요소 :" + list[2].data);
        }
    }

    public class SingleLinkedList
    {
        public Node head;
        public Node this[int i] { 
            get
            {
                Node tmp = head;
                for(int x = 0;x < i; x++)
                {
                    tmp = tmp.next;
                }
                return tmp;
            }
            set {
                Node tmp = head;
                for (int x = 0; x < i; x++)
                {
                    tmp = tmp.next;
                }
                tmp = value;


            } }
        public SingleLinkedList()
        {
            
        }
        public void Add(Node node)
        {
            if(head == null)
            {
                head = node;
            }
            else
            {
                Node tmp = head;
                while(tmp.next != null)
                {
                    tmp = tmp.next;
                }
                tmp.next = node;
            }
        }
        public void Print()
        {
            Node tmp = head;
            while(tmp != null)
            {
                Console.WriteLine(tmp.data);
                tmp = tmp.next;
            }            
        }

    }
    public class Node
    {
        public string data;
        public Node next;
        public Node(string data)
        {
            this.data = data;
        }
    }
}
728x90