본문 바로가기

LeetCode/Linked List

(6)
[Easy] 21. Merge Two Sorted Lists #문제 설명 #문제 풀이 #Iterative 풀이 public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode handler = head; while(l1 != null && l2 != null) { if (l1.val
[Medium] 142. Linked List Cycle II Leetcode 142번 문제에서는 Linked List가 주어지고, 주어진 Linked List에서 cycle이 발생하는지 알아내고, 발생하면 발생 지점의 노드를 반환하고, cycle이 발생 하지 않으면 null를 return해주면 된다. #풀이 public class Solution { public ListNode detectCycle(ListNode head) { HashSet hs = new HashSet(); boolean dup = false; while(head != null){ if(!hs.add(head)){ //HashSet에 add가 중복이 발생해 false return시 현재노드 반환 return head; } head = head.next; } return null; } } 이 풀..
[Easy] 141. Linked List Cycle Leetcode 141번 문제는 주어진 Linkedlist에 cycle ,즉 순환인 발생하는지 알아내는 문제이다. 위의 예제처럼 어느 한 노드에서 뒤에 노드로 뒤돌아가 반복된다면 cycle이 발생한 것이므로 true를 return 하면 된다. #풀이 Hashset을 사용한 풀이 public class Solution { public boolean hasCycle(ListNode head) { HashSet set = new HashSet(); boolean isCycle = false; while(head != null){ isCycle = set.add(head); head = head.next; if(!isCycle){ return !isCycle; } } return !isCycle; } } Set..
[Easy] 206. Reverse Linked List Leetcode 206번 문제는 주어진 연결 리스트를 반대로 뒤집는 문제이다. 연결 리스트의 reference to the head가 주어진다. #풀이 # Iteratively (반복) 풀이 class Solution { public ListNode reverseList(ListNode head) { ListNode prev = null; while(head != null){ ListNode nextNode = head.next; head.next = prev; prev = head; head = nextNode; } return prev; } } # recursively (재귀적) 풀이 class Solution { public ListNode reverseList(ListNode head) { //..
[Medium] 2. Add Two Numbers Leetcode 2번 문제는 순서가 거꾸로 된 2개의 연결 리스트를 더하는 문제이다. 연결 리스트의 각 노드 들은 한자리 숫자 만을 가지고 있다. public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sentinel = new ListNode(0); ListNode current = sentinel; int sum = 0; while (l1 != null || l2 != null) { sum /= 10; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } current.nex..
[Easy] 234. Palindrome Linked List Leetcode 234번 문제는 주어진 linkedlist 가 palindrome(회문) 인지 아닌지 판단하는 문제이다. 여기서 palindrome은 거꾸로 읽어도 똑바로 읽어도 같은 문자열이다. 예)기러기, 토마토, 스위스, 인도인, 별똥별, 우영우. #ArrayList 사용법 class Solution { public boolean isPalindrome(ListNode head) { ArrayList al = new ArrayList(); ListNode current = head; while(current !=null){ al.add(current.val); current = current.next; } int i = 0, j = al.size() - 1; while(i < j){ if(al.ge..