문제 👉 <Middle of the Linked List - LeetCode>
1. 문제 (링크드리스트의 중간)
링크드리스트의 중간을 반환하라.
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
2. 풀이
런너기법
를 이용한 풀이
- 워커 러너 테크닉
- walker : 한번에 한칸씩
- runner : 한번에 두칸씩
- runner가 끝나면 walker는 중간에 위치
3. 코드
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode runner = head;
while (runner != null && runner.next != null) {
runner = runner.next.next;
head = head.next;
}
return head;
}
}
- 결과 :
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
05/03/2021 | Accepted | 0 ms | 36.6 MB | java |
References
🏋🏻 개인적으로 공부한 내용을 기록하고 있습니다.
잘못된 부분이 있다면 과감하게 지적해주세요!! 🏋
'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 218. The Skyline Problem [JAVA(자바)] (0) | 2021.11.24 |
---|---|
[LeetCode] 589. N-ary Tree Preorder Traversal [JAVA(자바)] (0) | 2021.11.24 |
[LeetCode] 530. Minimum Absolute Difference in BST [JAVA(자바)] (0) | 2021.11.24 |
댓글