자바는 포인터가 없기 때문에 C언어와 같이 포인터를 사용한 링크드 리스트는 구현할 수 없다.
그러나 클래스 디자인을 통해 유사하게 구현할 수 있다.
또는 Collection 안에 내재되어있는 LinkedList 자료구조를 사용해도 된다.
컬렉션 사용은 아래 참조
https://cuddlyciel.tistory.com/34
[Collection] List컬렉션 - ArrayList, LinkedList
List컬렉션 -객체를 일렬로 늘어놓은 구조 -객체를 인덱스로 관리 -> 객체를 저장하면 자동 인덱스가 부여 -인덱스로 객체를 검색, 삭제할 수 있는 기능 제공 List컬렉션의 공통사용 가능한 메소드 기능 메소드 설..
cuddlyciel.tistory.com
자바로 구현된 코드
class Node {
private String value;
public Node link;
public Node(String data){
this.value = data;
this.link = null;
}
public String getValue(){
return this.value;
}
}
public class LinkedList {
private Node head;
public LinkedList(){
this.head = null;
}
public Boolean searchValue(String data){
Node tmp = this.head;
while(tmp != null){
if(tmp.getValue().equals(data)){
return true;
}
else{
tmp = tmp.link;
}
}
return false;
}
public void insertNode(String search, String data){
Node node = new Node(data);
Node tmp = this.head;
while(tmp != null){
if(tmp.getValue().equals(search)){
break;
}
else{
tmp = tmp.link;
}
}
if(tmp != null){
node.link = tmp.link;
tmp.link = node;
}
else{
insertNode(data);
}
}
public void insertNode(String data){
Node node = new Node(data);
if(head == null){
head = node;
}
else{
Node tmp = head;
while(tmp.link != null){
tmp = tmp.link;
}
tmp.link = node;
}
}
public void printValues(){
Node tmp = this.head;
while(tmp != null){
System.out.println(tmp.getValue());
tmp = tmp.link;
}
}
public void deleteNode(String data){
if(searchValue(data)){
Node tmp = this.head;
Node preNode = tmp;
while(tmp != null){
if(tmp.getValue().equals(data)){
preNode.link = tmp.link;
System.out.println("delete complete");
break;
}
else{
preNode = tmp;
tmp = tmp.link;
}
}
}
else{
System.out.println("no data to delete");
}
}
public static void main(String[] args) {
LinkedList linkedlist = new LinkedList();
linkedlist.insertNode("A");
linkedlist.insertNode("B");
linkedlist.insertNode("C");
linkedlist.insertNode("D");
linkedlist.insertNode("F", "E");
linkedlist.printValues();
System.out.println(linkedlist.searchValue("B"));
linkedlist.deleteNode("C");
linkedlist.printValues();
}
}
'Java > Java이론' 카테고리의 다른 글
[Java 문법] 제네릭 (Generic) (0) | 2019.04.08 |
---|---|
[Java 문법] 예외 처리(Exception) (0) | 2019.04.08 |
[Java 문법] 패키지 (Package) (0) | 2019.04.08 |
[Java 문법] 내부 클래스 (Inner Class) (0) | 2019.04.08 |
[Java 문법] 다형성 (polymorphism) (0) | 2019.04.05 |