Middle of the Linked List Solutions in C++
Number 876
Difficulty Easy
Acceptance 68.5%
Link LeetCode
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description//// Author : liuyubobobo/// Time : 2018-08-02#include <iostream>#include <vector>using namespace std;/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/// Using Array/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:ListNode* middleNode(ListNode* head) {vector<ListNode*> nums;ListNode* cur = head;while(cur != NULL)nums.push_back(cur), cur = cur->next;return nums[nums.size() / 2];}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description//// Author : liuyubobobo/// Time : 2018-07-28#include <iostream>using namespace std;/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/// Two Linear Scans/// Calculate length and get the answer/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:ListNode* middleNode(ListNode* head) {int len = 0;ListNode* cur = head;while(cur != NULL)len ++, cur = cur->next;if(len == 1)return head;int k = len / 2;cur = head;for(int i = 0 ; i < k ; i ++)cur = cur->next;return cur;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/middle-of-the-linked-list/description//// Author : liuyubobobo/// Time : 2018-08-02#include <iostream>using namespace std;/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/// Fast and Slow Pointers/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:ListNode* middleNode(ListNode* head) {if(head == NULL || head->next == NULL)return head;ListNode* fast = head;ListNode* slow = head;while(fast && fast->next) {slow = slow->next;fast = fast->next->next;}return slow;}};int main() {return 0;}