자료구조/수업내용

03/30 단일연결리스트 복습 Add, Count, Print

박준희 2021. 3. 30. 10:12

 

단일 연결리스트의 노드 추가, 노드 갯수 취득, 노드 출력 기능 구현

 

Program.cs

using System;

namespace Study09
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main");
            new App();
        }
    }
}

 

App.cs

using System;

namespace Study09
{

    public class App
    {

        //생성자 
        public App()
        {
            SingleLinkedList linkedList = new SingleLinkedList();
            Node node1 = new Node(1);
            Node node2 = new Node(2);
            Node node3 = new Node(3);
            Node node4 = new Node(4);
            linkedList.Add(node1);
            linkedList.Add(node2);
            linkedList.Add(node3);
            linkedList.Add(node4);
            Console.WriteLine("---------------------------------------");
            Console.WriteLine("노드의 갯수 :" + linkedList.Count());
            Console.WriteLine("---------------------------------------");
            Console.WriteLine("노드의 데이터");
            linkedList.Print();
            Console.WriteLine("\n---------------------------------------");
        }

    }
}

 

 

SingleLinkedList.cs

using System;

namespace Study09
{
    public class Node
    {
        public int data;
        public Node next;
        public Node(int data)
        {
            this.data = data;
        }
    }
    public class SingleLinkedList
    {
        private Node head;
        public SingleLinkedList()
        {

        }

        public void Add(Node newNode)
        {
            if(head == null)
            {
                head = newNode;
            }
            else
            {
                if(head.next == null)
                {
                    head.next = newNode;
                }
                else
                {
                    Node current = head.next;
                    while(current != null && current.next != null)
                    {
                        current = current.next;
                    }
                    current.next = newNode;
                }
            }
        }

        public int Count()
        {
            int count = 0;
            Node current = this.head;
            while(current != null)
            {  
                count++;
                current = current.next;
            }
            return count;
        }

        public void Print()
        {
            Node current = this.head;
            while(current != null)
            {
                Console.Write(current.data + " ");
                current = current.next;
            }
        }
    }
}