자료구조 - Singly Linked List 구현

싱글 링크드 리스트 구현해보는 포스팅입니다.

Singly Linked List는 각 Node를 단방향으로 연결합니다.

각 Node는 데이터와 다음 연결될 Node를 가진다.

맨 처음 Node는 head 입니다.

Node.next 가 null 이면 LinkedList의 tail 마지막 값입니다.

코드
자바입니다.

public class SinglyLinkedList{
	private ListNode head; //
    
    //It contains a static inner class ListNode
    private static class ListNode{
    	private int data; //Generic Type
        private ListNode next;
        
        public ListNode(int data){
        	this.data = data;
            this.next = null;
        }
    }
    
    public static void main(String[] args){
    	//Lets create a linked list demonstrated in slide
        //10 --> 8 --> 1 --> 11 --> null
        //10은 LinkedList Node의 head 값입니다. 
        
        //ListNode head = new ListNode(10);
        SinglyLinkedList sil = new SinglyLinkedList();
        sill.head = new ListNode(10);
        ListNode second = new ListNode(8);
        ListNode third = new ListNode(1);
        ListNode fourth = new ListNode(11);
        
        //각 노드들을 연결합니다.
        sil.head.next = second; // 10 --> 8 --> null
        second.next = third; // 10 --> 8 --> 1 -->null
        third.next = fourth; //10 --> 8 --> 1 --> 11 --> null
    
    	sil.display();//10 --> 8 --> 1 --> 11 --> null
    }
    
    //ListNode display
    public void display(){
    	ListNode current = head;
        while(current != null){
         	System.out.print(current.data + " --> ");
        	current = current.next;
        }
        System.out.print("null");
   }
 }

참고
https://www.youtube.com/watch?v=-j6LVWmyCCU

좋은 웹페이지 즐겨찾기