LeetCode_Study_Plan/Algorithm
876. Middle of the Linked List java
개발하는루루
2022. 12. 21. 00:06
https://leetcode.com/problems/middle-of-the-linked-list/
Middle of the Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/**
* 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 temp = head;
int n = 0;
for (; temp != null; temp = temp.next) {
n++;
}
for (int i = 0; head != null; head = head.next) {
if (i == Math.round(n/2)) {
return head;
}
i++;
}
return head;
}
}