-
[LeetCode] 876. Middle of the Linked List c++Coding Test/LeetCode 2022. 12. 26. 18:45728x90
- 문제
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'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 3. Longest Substring Without Repeating Characters c++ (0) 2022.12.27 [LeetCode] 19. Remove Nth Node From End of List c++ (0) 2022.12.27 [LeetCode] 557. Reverse Words in a String III c++ (0) 2022.12.26 [LeetCode] 344. Reverse String c++ (0) 2022.12.26 [LeetCode] 167. Two Sum II - Input Array Is Sorted c++ (0) 2022.12.26