-
[Data Structure] Java ๋งํฌ๋ ๋ฆฌ์คํธ(LinkedList) ๊ตฌํData Structure 2021. 1. 15. 10:55๋ฐ์ํ
- ์ด ๊ธ์ "์จ๋ผ์ธ ์๋ฐ ์คํฐ๋ ๋ด์ฉ"์ ์ ๋ฆฌํ ๊ธ์ ๋๋ค.
LinkedList๋?
- ๋งํฌ๋ ๋ฆฌ์คํธ๋ฅผ ๋ ธ๋์ ๋ ธ๋๋ฅผ ์ฐ๊ฒฐํ์ฌ ๋ฐ์ดํฐ๋ฅผ ๋ด๋ ๋ฐฉ์์ธ ์๋ฃ๊ตฌ์กฐ์ ๋๋ค.
- ๋งํฌ๋ ๋ฆฌ์คํธ์ ๋ฉค๋ฒ๋ณ์๋ก ๋ฐ์ดํฐ์ ํฌ์ธํฐ๊ฐ ์กด์ฌํ์ฌ ํฌ์ธํฐ๋ก ๋ค์ ๋ ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ ๋ฐฉ์์ ๋๋ค.
- ๋งํฌ๋ ๋ฆฌ์คํธ์ ๋ฐฐ์ด๊ณผ์ ์ฐจ์ด์ ์ ๋ช ๋ฐฑํ ์กด์ฌํฉ๋๋ค. ๋ฐฐ์ด์ ํ ์ค๋ก ๋์ด๋ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ๋ด๋ ์๋ฃ๊ตฌ์กฐ๋ก ์ธ๋ฑ์ค๋ก ๋ฐ์ดํฐ์ ์ ๊ทผ ํ ์ ์์ต๋๋ค.
- ํ์ง๋ง ๋ฐฐ์ด์ ์ถ๊ฐ, ์ญ์ ๊ฐ ์ฉ์ดํ์ง ์์ต๋๋ค. ๋ฐ๋ฉด, ๋งํฌ๋ ๋ฆฌ์คํธ๋ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ๊ณผ ์๊ด์์ด ํ๋์ ๋ ธ๋๋ผ๋ฆฌ ์ฐ๊ฒฐํ๋ค ๋ณด๋ ๋ฉ๋ชจ๋ฆฌ ์ฌ์ฉ ์ธก๋ฉด์์ ํจ์จ์ ์ ๋๋ค. ์ถ๊ฐ, ์ญ์ ๋ ์ฉ์ดํ์ง๋ง ์ธ๋ฑ์ค๊ฐ ์์ด ํ์ํ๊ธฐ์๋ ์ ํฉํ์ง ์์ต๋๋ค.
LinkedList ๊ตฌํ
์๋ฐ์์ ์ธ์คํด์ค ์ ๋ฌ์ ๋ ํผ๋ฐ์ค์ ๋๋ค
- ์ฐธ์กฐ(https://shyunku.tistory.com/38)
public class ListNode { int data; ListNode next; public ListNode(int data) { this.data = data; next = null; } }
๋จผ์ ListNode๋ฅผ ๊ตฌํํ์ฌ data์ ๋ค์ ๋ ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ next๋ฅผ ๊ฐ์ง๋๋ก ํด๋์ค๋ฅผ ์์ฑํฉ๋๋ค.
๋ค์ ๋ ธ๋๋ก ์ฐ๊ฒฐํ์ฌ ํ๋์ ์ฐ๊ฒฐ๋ฆฌ์คํธ๊ฐ ์์ฑํ๋ ๊ฒ์ ๋๋ค.This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic class LinkedList { int size; public LinkedList() { size = 0; } public int getSize() { return size; } ListNode add(ListNode head, ListNode nodeToAdd, int position) { ListNode node = head; if(size<position){ return null; } if (head == null) { node = nodeToAdd; head = node; } else { for (int i = 1; i < position; i++) { node = node.next; } nodeToAdd.next = node.next; node.next = nodeToAdd; } size++; return head; } ListNode remove(ListNode head,int positionToRemove){ ListNode node = head; if(size<=positionToRemove || head == null){ return null; } if(positionToRemove == 0){ node = node.next; head = node; } else{ for(int i=1;i<positionToRemove;i++){ node = node.next; } node.next = node.next.next; } size--; return head; } boolean contains(ListNode head, ListNode nodeTocheck){ ListNode node = head; boolean check = false; if(head == null){ return false; } do{ if(node.data == nodeTocheck.data && node.next == nodeTocheck.next){ check = true; break; } node = node.next; }while(node!=null); return check; } } - ListNode add(ListNode head, ListNode nodeToAdd, int position) : head๋ ๋งํฌ๋ ๋ฆฌ์คํธ์ ๋งจ ์ ๋ ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ฉฐ nodeToAdd ๋ ธ๋๋ฅผ ํด๋น position์ ์ถ๊ฐํ๋ ํจ์
- ListNode remove(ListNode head, int positionToRemove) : ๋งํฌ๋ ๋ฆฌ์คํธ์์ positionToRemove์ ํด๋นํ๋ ์์น์ ๋ฐ์ดํฐ๋ฅผ ์ญ์ ํ๋ ํจ์
- boolean contains(ListNode head, ListNode nodeTocheck) : ๋งํฌ๋ ๋ฆฌ์คํธ์์ nodeTocheck ๋ ธ๋๊ฐ ์๋์ง ํ์ธํ๋ ํจ์
๋ฐ์ํ'Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] Java ํ(Queue) ์ฌ์ฉ (0) 2021.01.15 [Data Structure] Java ์คํ(Stack) ์ฌ์ฉ (0) 2021.01.15 [Data Structure] multimap ์ฌ์ฉ๋ฒ (0) 2020.11.08 [Data Structure] Set ์ฌ์ฉ๋ฒ (0) 2020.03.19 [Data Structure] unordered_map ์ฌ์ฉ๋ฒ (6) 2020.03.16