C#/자료구조

0329 _ 단일연결 리스트 (2단계까지) /

minquu 2021. 3. 29. 18:05
반응형

연결리스트 
데이터와 포인터를 가지고있다.노드들이 한 줄로 쭉 연결되어 있는 방식으로 데이터를 저장하는 자료 구조
노드가 데이터와 포인터를 가지고잇다.
노드들이 한 방향으로 각 노드가 다음 노드를 가리키고있는 리스트는 단일 연결리스트
각 노드가 이전 노드와 다음 노드를 모두 가리키는 양방향은 이중 연결 리스트
포인터는 우리가 알고있는 참조이다.

단일 연결 리스트를 구현하기 위해서는 먼저 노드 클래스와 이를 연결한 링크드리스트클래스가 필요한다.
기본적으로 데이타 필드와 그 다음 노드를 가리키는 포인터로 만들어져있다.

단일 연결 리스트 클래스는 리스트의 첫 노드를 가리키는 헤드 head필드를 가지게 되는데,
이 head를 사용하여 전체 리스트를 순차적으로 엑세스하게된다.

 

1.노드 생성

2. head의 변수 선언, 후 Add하는 메서드 추가 후 Head가 null 일시 head에 node 추가하기

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

--------

 

 

 

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study16
{
    public class Node
    {
        public int data;
        public Node next;
        public Node(int data)
        {
            this.data = data;
        }
    }
    public class SingleLinkedList
    {
        private Node head; //head 부터 순차적 접근하기 위함

        //생성자
        public SingleLinkedList()
        {
        }
        //노드 추가
        public void Add(Node node)
        {
            if (this.head == null)
            {
                this.head = node;
            }
            else
            {
                //head부터 찾아서 next가 null 인 것 찾기
                //비교대상을 임시저장
                Node current = this.head;
                while (current != null && current.next != null)
                {
                    //next가 있음.
                    current = current.next; // 커렌트가 있네? 다음 커렌트를 넣고 비교
                }
                //새로운 노드 연결
                current.next = node;
            }
        }
        //노드 수 세기
        public int Count()
        {
            int count = 0;
            Node current = this.head;
            while (current != null)
            {
                count++;
                current = current.next;
            }
            return count;
        }

        //노드 추가
        public void AddAfter(Node current, Node newNode) {
            if (this.head == null || current == null || newNode == null) {
                throw new InvalidOperationException();
            }
            newNode.next = current.next; // 뉴노드의 넥스트를 커런트의 넥스트로 바꾼다.
            current.next = newNode; // 그리고 커런트의 넥스트를 뉴노드로 한다.
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Study16
{
    public class App
    {
        public App()
        {
            SingleLinkedList list = new SingleLinkedList();
            var head = new Node(1);
            list.Add(head);
            list.Add(new Node(2));
            list.AddAfter(head, new Node(3));
            Console.WriteLine(list.Count());
        }

    }
}



 

반응형