From 066881a3efee9ad36fabb158c725893d46c71c48 Mon Sep 17 00:00:00 2001 From: Anup Deshpande Date: Wed, 8 Apr 2020 11:24:11 -0400 Subject: [PATCH] add MiddleOfTheLinkedList solution --- LinkedList/MiddleOfTheLinkedList.swift | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LinkedList/MiddleOfTheLinkedList.swift diff --git a/LinkedList/MiddleOfTheLinkedList.swift b/LinkedList/MiddleOfTheLinkedList.swift new file mode 100644 index 00000000..05f93879 --- /dev/null +++ b/LinkedList/MiddleOfTheLinkedList.swift @@ -0,0 +1,28 @@ +/** + * Question Link: https://leetcode.com/problems/middle-of-the-linked-list/ + * Primary idea: Add all ListNodes to an array, then return the middle node. + * Time Complexity: O(n), Space Complexity: O(n) + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init(_ val: Int) { + * self.val = val + * self.next = nil + * } + * } + */ +class Solution { + func middleNode(_ head: ListNode?) -> ListNode? { + + var list = [ListNode]() + var current = head + + while current != nil{ + list.append(current!) + current = current?.next + } + + return list[list.count/2] + } +}