1 Nisan 2020 Çarşamba

Linked List Orta Nokta


https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3290/






>> Solution 1 : Find Size, Then Middle

O(n) time, O(1) space


--
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class LinkedListMiddleNode {
public ListNode solve(ListNode head) {
int size = 0;
// Go to the last node to find the size
ListNode current = head;
while(current != null) {
current = current.next;
size++;
}
int middle = size/2;
// Go to the middle node
current = head;
for(int i=0; i < middle; i++) {
current = current.next;
}
return current;
}
}
--





>> Solution 2 : Slow and Fast Pointer

O(n) time, O(1) space

--
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class LinkedListMiddleNodeFastPointer {
public ListNode middleNode(ListNode head) {
ListNode sizePointer = head;
ListNode middlePointer = head;
while(sizePointer != null && sizePointer.next != null) {
middlePointer = middlePointer.next;
sizePointer = sizePointer.next.next;
}
return middlePointer;
}
}
--


Hiç yorum yok: