Java/Java이론

[Java] 자바로 링크드 리스트 구현하기(Implementing Linked List with Java)

자바는 포인터가 없기 때문에 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();
	}
}