본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 872. Leaf-Similar Trees

반응형

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

 

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

자료구조에 대한 이해를 토대로 구현한 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

linked list는 index로 접근할 수 없어 가운데에 해당하는 index를 얻기 위해 함수를 구현했습니다.head를 순회하며 가운데 index를 반환할 getMiddleIndex함수를 수행합니다.

📔 풀이과정

정답 ListNode ans를 선언 후 getMiddleIndex로 중간 원소의 index를 얻어 해당 index만큼 next를 호출해 이동해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getMiddleIndex(ListNode*head){
        ListNode * cur = head;
        int totalIndex = 0;
        while(cur != NULL) {
            totalIndex++;
            cur = cur->next;
        }
        return totalIndex/2;
    }
    ListNode* middleNode(ListNode* head) {
        ListNode*ans = head;
        int cnt = 0;
        int middleIndex = getMiddleIndex(head);
        while(cnt != middleIndex) {
            ans=ans->next;
            cnt++;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.