I am trying to solve LeetCode problem 143. Reorder List:
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln − 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln − 1 → L2 → Ln − 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
This is my attempt at it:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return;
}
ListNode n1 = head;
ListNode temp = null;
while (n1.next.next != null) {
n1 = n1.next;
}
temp = n1.next;
n1.next = null;
temp.next = head.next;
head.next = temp;
reorderList(temp.next);
}
}
I'm unable to come up with concrete reasoning for the time complexity of my code. My brain says O(n^2) but I just can't justify the why. How can the time complexity be derived?