Middle of the Linked List

ㅋㅋ·2022년 12월 5일
0

알고리즘-leetcode

목록 보기
62/135

링크드 리스트의 헤드 노드를 받고 해당 리스트에서 절반의 시작 노드를 구하는 문제

/**
 * 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:
    ListNode* middleNode(ListNode* head) {
        
        vector<ListNode *> save(100);
        ListNode *node{head};
        int counter{0};
        
        while (node != NULL)
        {
            save[counter++] = node;
            node = node->next;
        }

        return save[(counter >> 1)];
    }
};

0개의 댓글