Coding Test/LeetCode

[LeetCode] 876. Middle of the Linked List c++

owls 2022. 12. 26. 18:45
728x90
  • 문제

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.

 

단일 링크로 이어져 있는 리스트에서 중간에 있는 노드를 구하는 문제입니다.

 

  • 문제 해결
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
       ListNode *fast = head, *slow = head;
        while(fast){
            fast = fast->next;
            if(fast){
                fast = fast->next;
            }
            else{
                break;
            }
            slow = slow->next;
        }
        return slow;
    }
};

 

다른 풀이

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

 

 

728x90