코딩인터뷰
-
Linked List | Partition ListAlgorithm/Linked List 2021. 7. 19. 23:07
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. 주어진 Linked List를 파티션 하라는 문제이다. Integer 값이 주어지는데, 이보다 작으면 순서대로 왼쪽에, 크거나 같으면 순서대로 오른쪽에 나열해서 새로운 Linked List를 리턴하는 문제이다. Dummy Node를 이용해서 손쉽게 풀 수 있다. /** * Definition for ..
-
Linked List | Swap Nodes in PairsAlgorithm/Linked List 2021. 7. 12. 15:45
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 2 노드씩 짝을 지어서, 순서를 바꾸라는 문제이다. 또한, 값을 변형하는것이 아닌, 노드의 위치를 바꾸라는 문제이다. 만약 노드의 갯수가 0개, 1개일 경우는 그대로 리턴해야하며, 노드 갯수가 홀수일 때, 마지막 노드는 그대로 둔다. 한번의 Trip만에 해결할 수 있는 방식이 떠올라 바로 코딩을 했다. 해법은 아래와 같다. class Solution { publi..
-
Linked List | Reverse Linked ListAlgorithm/Linked List 2021. 4. 29. 23:27
Given the head of a singly linked list, reverse the list, and return the reversed list. 말 그대로, head노드를 가지고 Linked List를 reverse해서, 새로운 head를 리턴하는 문제다. 모두 오른쪽을 바라보다가, 순차적으로 왼쪽을 바라보게 하는 그림을 연상시킨다. 이 문제를 한큐만에, O(N)으로 푸는 방법이 있다. 바로 지나가면서 뒤집는 방법이다. 코드는 다음과 같다. class Solution { public ListNode reverseList(ListNode head) { ListNode newNext = null; ListNode temp = null; ListNode curr = head; while(curr ..