티스토리 뷰

Data Structure & Algorithm

[Java] LinkedList

Alledy 2019. 5. 31. 13:46

LinkedList

package LinkedList;

// 노드는 data와 다음 오브젝트를 가리킬 next variable로 구성됨
public class Node {
	int data;
	Node next = null; 
}


public class App {
	public static void main(String[] args) {
        // 노드 인스턴스 생성 및 데이터 삽입
		Node nodeA = new Node();
		nodeA.data = 3;
		
		Node nodeB = new Node();
		nodeB.data = 5;

		Node nodeC = new Node();
		nodeC.data = 7;

		Node nodeD = new Node();
		nodeD.data = 9;
		
        // 노드 인스턴스끼리의 연결 
		nodeA.next = nodeB; 
		nodeB.next = nodeC;
		nodeC.next = nodeD;
		
		System.out.println(listLength(nodeA)); // prints 4
		System.out.println(listLength(nodeB)); // prints 3
	}
	
    // linkedList의 길이를 리턴하는 메서드
	public static int listLength(Node aNode) {
		Node currentNode = aNode; 
		int len = 0; 
		while(currentNode != null) {
			len++;
			currentNode = currentNode.next; 
		}
		return len; 
	}
	
}

 

Singly LinkedList

package ds.singlylinkedlist;

public class Node {
	public int data;
	public Node next;
	
	public void displayNode() {
		System.out.println("{ " + data + " }");
	}
}

public class SinglyLinkedList {
	private Node first; 
	
	public SinglyLinkedList() {
		
	}
	
	public boolean isEmpty() {
		return first == null; 
	}
	
	public void insertFirst(int data) {
		Node newNode = new Node();
		newNode.data = data;
		newNode.next = first; 
		first = newNode; 
	}
	
	public Node deleteFirst() {
		Node temp = first;
		first = first.next; 
		return temp ;
	}
	
	public void displayList() {
		System.out.println("List (first --->last)  ");
		Node current = first;
		while(current != null) {
			current.displayNode();
			current = current.next;
		}
		System.out.println();
	}
}

package ds.singlylinkedlist;

public class App {
	public static void main(String[] args) {
		SinglyLinkedList mylist = new SinglyLinkedList(); 
		mylist.insertFirst(100);
		mylist.insertFirst(50);
		mylist.insertFirst(90);
		mylist.insertFirst(80);
		
		mylist.displayList();
	}
}

 

'Data Structure & Algorithm' 카테고리의 다른 글

[파이썬] 야근지수 문제  (1) 2019.09.23
[JS] 가장 먼 노드(그래프 탐색)  (0) 2019.07.02
[Java] Queue  (0) 2019.05.27
[Java] Stack, reverseString  (0) 2019.05.27
자바_셀프넘버  (0) 2019.05.15
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함