LeetCode - 876. Middle of the Linked List(Linked List, Two Pointers)

YAMAMAMO·2022년 9월 28일
0

LeetCode

목록 보기
57/100

문제

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.

https://leetcode.com/problems/middle-of-the-linked-list/

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

풀이

class Solution {
    public ListNode middleNode(ListNode head) {
   	    int length = returnLength(head);
        int start = length/2+1;
        return returnSecond(head, start);
    }
    //길이를 반환
    public int returnLength(ListNode head){
        int length=0;
        while(head!=null){
            head=head.next;
            length++;
        }
        return length;
    }
    //중간 노드 반환
    public ListNode returnSecond(ListNode head, int start){
        while(start!=1){
            head=head.next;
            start--;
        }
        return head;
    }    
}

////투포인터
class Solution {
    public ListNode middleNode(ListNode head) {
        
        ListNode fast = head;
        ListNode slow = head;
        
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    
}
profile
안드로이드 개발자

0개의 댓글