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();
}
}