코딩테스트 풀이/JAVA
[LeetCode/Easy] 876. Middle of the Linked List
무지맘
2023. 5. 31. 14:48
1. Input
1) ListNode head
2. Output
1) 연결 리스트의 중간을 찾아 반환
- 중간이 2개라면 2번째 중간을 반환
3. Constraint
1) 리스트의 노드 수의 범위는 [1, 100]이다.
2) 1 <= Node.val <= 100
4. Example
Input: head = [1,2,3,4,5] -> Output: [3,4,5]
Input: head = [1,2,3,4,5,6] -> Output: [4,5,6]
5. Code
1) 첫 코드(2023/05/31)
/**
* 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 n = head;
int count = 0;
while(n!=null){
count++;
n = n.next;
}
int i = 0;
while(i++<count/2)
head = head.next;
return head;
}
}
- 100%, 65%