๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/LeetCode

[LeetCode] 876. Middle of the Linked List (java)

by sun_HY 2023. 10. 30.
Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
example

 

 

#๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ  #ํˆฌํฌ์ธํ„ฐ

 

 

 

submission detail

 

์ฃผ์–ด์ง„ ๋ฆฌ์ŠคํŠธ์˜ ์ „์ฒด ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๊ณ  ์ ˆ๋ฐ˜๊นŒ์ง€ ๋„๋‹ฌํ•  ๋•Œ๊นŒ์ง€ next๋กœ ์ด๋™ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ’€์—ˆ๋‹ค.

๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ด ์ข‹์ง€ ์•Š์•„์„œ ํ™•์ธํ•ด๋ณด๋‹ˆ ํˆฌํฌ์ธํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ๋ณต์‚ฌํ•ด์„œ ๊ธธ์ด๋ฅผ ๊ตฌํ•  ํ•„์š” ์—†์ด

์ธ๋ฑ์Šค๋งŒ ์ด์šฉํ•ด์„œ ํ•œ ๋ฐ”ํ€ด๋งŒ ๋Œ๊ฒŒ ํ‘ธ๋Š” ๊ฒŒ ๋” ํšจ์œจ์ ์ธ ๋ฐฉ๋ฒ•์ธ ๋“ฏ!

 

 

class Solution {
    public ListNode middleNode(ListNode head) {
        int length = 1;
        int half;
        int cur = 0;
        ListNode h;
        h = head;
        
        // ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด ๊ตฌํ•˜๊ธฐ
        while (h.next != null) {
            h = h.next;
            length++;
        }

        half = length / 2;
        while (cur < half) {
                cur++;
                head = head.next;
            }
        return head;

    }
}
 

 

 

 

Middle of the Linked List - LeetCode

Can you solve this real interview question? Middle of the Linked List - Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.   Example 1: [https://assets.leetcode.

leetcode.com

 

728x90