Notice
Recent Posts
Recent Comments
Link
«   2025/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
Tags
more
Archives
Today
Total
관리 메뉴

햄발

LinkedList 본문

Java

LinkedList

햄발자 2024. 5. 22. 17:04

 

 

 

LinkedList

 

특징

  • 동일한 데이터 타입을 순서에 따라 관리하는 자료 구조
  • 자료를 저장하는 노드에는 자료와 다음 요소를 가리키는 링크(포인터)가 있음
  • 자료가 추가 될때 노드 만큼의 메모리를 할당 받고 이전 노드의 링크로 연결함 (정해진 크기가 없음)
  • jdk 클래스 : LinkedList

 

 

 

 

 

하나의 요소를 저장하는 기능 설계

 

코드예시

package structure.ch04;

public class MyLinkedList {
	
	private Node head; // 요소의 맨 처음을 가리킴 
	private int count; // 링크드리스트에 몇개의 요소가 연결 되어 있는 개수
	
	// MyLinkedList 맨 처음 생성시 노드는 없는 상태 
	public MyLinkedList() {
		head = null;
		count = 0;
	}
	
	// 저장된 Node 갯수를 반환하는 메서드 
	public int getCount() {
		return count;
	}
	
	// 새로운 노드(Node)를 1개 추가 하는 메서드를 만들자. 
	public Node addElement(String data) {
		Node createNode = new Node(data);
		
		if(head == null) {
			// 제일 처음 요소를 저장하는 동작
			head = createNode;
		} else {
			// 요소 찾기는 head 부터 시작 
			Node preNode = head; // [][](next) 
			// [앵무][] ---> [오리][] --> [구구][]
			while(preNode.next != null) {
				preNode = preNode.next;
			}
			// 핵심 코드 
			//[오리][next] --> [next] =  [구구][]
			preNode.next = createNode;
		}
		
		count++; 
		return createNode; // 추후 수정 
	}
	
	// 테스트 코드 
	public static void main(String[] args) {
		MyLinkedList linkedList = new MyLinkedList();
		linkedList.addElement("앵무");
		linkedList.addElement("오리");
		linkedList.addElement("구구");
		
		// [앵무][] ---> [오리][] ----> [구구][]
		
		
		System.out.println(linkedList.getCount());
		
		
	} // end of main 
	
	
	
} // end of class

 

 

 

 

특정 위치에 요소 삭제 하기

 

 

삭제 기능, 전체 출력 기능 추가

코드예시

 

package structure.ch04;

public class MyLinkedList {
	
	private Node head; // 요소의 맨 처음을 가리킴 
	private int count; // 링크드리스트에 몇개의 요소가 연결 되어 있는 개수
	
	// MyLinkedList 맨 처음 생성시 노드는 없는 상태 
	public MyLinkedList() {
		head = null;
		count = 0;
	}
	
	// 저장된 Node 갯수를 반환하는 메서드 
	public int getCount() {
		return count;
	}
	
	// 새로운 노드(Node)를 1개 추가 하는 메서드를 만들자. 
	public Node addElement(String data) {
		Node createNode = new Node(data);
		if(head == null) {
			// 맨 처음 요소를 저장하는 동작
			head = createNode;
		} else {
			// 항상 요소 찾기는 head 부터 시작 
			Node preNode = head; // [앵무][](next) 
			// [앵무][] ---> [오리][] --> [구구][]
			while(preNode.next != null) {
				preNode = preNode.next;
			}
			// 핵심 코드 
			//[오리][next] --> [next] =  [구구][]
			preNode.next = createNode;
		}
		
		count++; 
		return createNode; // 추후 수정 
	}
	
	public Node removeElement(int index) {
		// 방어적 코드 
		// 0 , 1 
		if(index >= count) {
			System.out.println("삭제할 위치 오류. 현재 리스트 개수는 " + count + " 입니다");
			return null;
		}
		
		// 맨 앞 요소를 삭제 요청 시 
		// 항상 요소를 찾을 때 시작은 head 부터 시작이다.
		Node tempNode = head;
		if(index == 0) {
			// 코드 시작전 모습
			head = tempNode.next;
			// 코드 수행 후 모습 
			// [오리][null]
		} else {
			// 코드 시작전 모습 : postion -> 2 라고 가정 --> n - 1 ---> [1] 
			Node preNode = null; 
			for(int i = 0; i < index; i++) {
				preNode = tempNode;
				tempNode = tempNode.next;
			}
			preNode.next = tempNode.next;
			
		} // end of if 
		count--;
		// System.out.println(positon + " 번째 요소를 삭제 했습니다.");
		return tempNode; // todo - 추후 수정 
	}
	
	// 전체 출력 하는 기능 만들기 
	public void printAll() {
		if(count == 0) {
			System.out.println("출력할 내용이 없습니다");
			return;
		}
		
		Node temp = head;
		while(temp != null) {
			System.out.print(temp.getData());
			temp = temp.next;
			if(temp != null) {
				System.out.print("-->");
			}
		}
		System.out.println();
	}

	
	// 테스트 코드 
	public static void main(String[] args) {
		MyLinkedList linkedList = new MyLinkedList();
		linkedList.addElement("앵무");
		linkedList.addElement("오리");
		linkedList.addElement("구구");
		linkedList.addElement("꼬꼬");
		linkedList.addElement("참새");
		
		linkedList.printAll();
		linkedList.removeElement(4);
		linkedList.printAll();
		// [앵무][] ---> [오리][] ----> [구구][]
		//System.out.println(linkedList.getCount());
		
		
	} // end of main 
	
	
	
} // end of class

 

 

 

하나의 요소 출력, 전체 삭제 기능 추가

코드예시

package structure.ch04;

import java.util.LinkedList;

public class MyLinkedList {
	
	private Node head; // 요소의 맨 처음을 가리킴 
	private int count; // 링크드리스트에 몇개의 요소가 연결 되어 있는 개수
	
	// MyLinkedList 맨 처음 생성시 노드는 없는 상태 
	public MyLinkedList() {
		head = null;
		count = 0;
	}
	
	// 저장된 Node 갯수를 반환하는 메서드 
	public int getCount() {
		return count;
	}
	
	// 새로운 노드(Node)를 1개 추가 하는 메서드를 만들자. 
	public Node addElement(String data) {
		Node createNode = new Node(data);
		if(head == null) {
			// 맨 처음 요소를 저장하는 동작
			head = createNode;
		} else {
			// 항상 요소 찾기는 head 부터 시작 
			Node preNode = head; // [야스오][](next) 
			// [앵무] ---> [오리][] --> [구구][]
			while(preNode.next != null) {
				preNode = preNode.next;
			}
			// 핵심 코드 
			//[오리][next] --> [next] =  [구구][]
			preNode.next = createNode;
		}
		
		count++; 
		return createNode; // 추후 수정 
	}
	
	public Node removeElement(int index) {
		// 방어적 코드 
		// 0 , 1 
		if(index >= count) {
			System.out.println("삭제할 위치 오류. 현재 리스트 개수는 " + count + " 입니다");
			return null;
		}
		
		// 맨 앞 요소를 삭제 요청 시 
		// 항상 요소를 찾을 때 시작은 head 부터 시작이다.
		Node tempNode = head;
		if(index == 0) {
			// 코드 시작전 모습
			head = tempNode.next;
			// 코드 수행 후 모습 
		} else {
			// 코드 시작전 모습 : postion -> 2 라고 가정 --> n - 1 ---> [1] 
			Node preNode = null; 
			for(int i = 0; i < index; i++) {
				preNode = tempNode;
				tempNode = tempNode.next;
			}
			preNode.next = tempNode.next;
			
		} // end of if 
		count--;
		// System.out.println(positon + " 번째 요소를 삭제 했습니다.");
		return tempNode; // todo - 추후 수정 
	}
	
	// 전체 출력 하는 기능 만들기 
	public void printAll() {
		if(count == 0) {
			System.out.println("출력할 내용이 없습니다");
			return;
		}
		
		Node temp = head;
		while(temp != null) {
			System.out.print(temp.getData());
			temp = temp.next;
			if(temp != null) {
				System.out.print("-->");
			}
		}
		System.out.println();
	}
	
	// 지정한 위치의 노드 하나만 출력 하기 
	public Node getNodeByIndex(int index) {
		if(index >= count) {
			System.out.println("검색 위치 오류 - 잘못된 요청");
		}
		
		Node tempNode = head;
		if(index == 0) {
			return head;
		}
		for(int i = 0; i < index; i++) {
			tempNode = tempNode.next; // 다음 요소는 무조건 next 에 담겨 있다.  
		}
		
		return tempNode; 
	}

	// 전체 삭제 기능 
	public void removeAll() {
		head = null;
		count = 0;
	}
	
	// 테스트 코드 
	public static void main(String[] args) {
		MyLinkedList linkedList = new MyLinkedList();
		linkedList.addElement("앵무");
		linkedList.addElement("오리");
		linkedList.addElement("구구");
		linkedList.addElement("꼬꼬");
		linkedList.addElement("참새");
		
		linkedList.printAll();
		linkedList.removeElement(4);
		linkedList.printAll();
		System.out.println(linkedList.getNodeByIndex(1).getData());
		// [앵무][] ---> [오리][] ----> [구구][]
		//System.out.println(linkedList.getCount());
		linkedList.removeAll();
		linkedList.printAll();
		
	} // end of main 
	
	
	
} // end of class

'Java' 카테고리의 다른 글

Java I/O  (0) 2024.05.23
Inner class  (0) 2024.05.23
Queue  (1) 2024.05.21
배열 활용  (5) 2024.05.03
자료구조 (Data Structure)  (1) 2024.05.02