iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 5

每日一LeetCode(5)

  • 分享至 

  • xImage
  •  

876.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://ithelp.ithome.com.tw/upload/images/20240204/20162696CwLQN33Lfe.png

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

Example 2:
https://ithelp.ithome.com.tw/upload/images/20240204/20162696yQLp2Ia1yh.png

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) {
        ListNode *slow = head, *fast = head;
        while(fast && fast -> next)
        {
            slow = slow -> next;
            fast = fast -> next -> next;
        }
        return slow;
    }
};

上一篇
每日一LeetCode(4)
下一篇
每日一LeetCode(6)
系列文
Leetcode 解題之旅:逐日攻克30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言