Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions LinkedListCycle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class LinkedListCycle {
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// 2(a + b) = a + b + k(c + b)
// a = (k -1 )b + kc
//
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null ) return null;
ListNode slow = head.next;
ListNode fast = head.next.next;

while (fast != slow) {
if(fast == null || fast.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}

if(fast == null || fast.next == null) {
return null;
}
slow = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return slow;


}
}
28 changes: 28 additions & 0 deletions RemoveNth.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class RemoveNth {
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
if(head == null || head.next == null) {
return null;
}
for(int i = 0; i <= n; i++) {
fast = fast.next;
}

while(fast != null) {
fast = fast.next;
slow = slow.next;
}
fast = slow.next;
slow.next = slow.next.next;


return dummy.next;

}
}
19 changes: 19 additions & 0 deletions ReverseList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class ReverseList {

// Time Complexity : O(n)
// Space Complexity : O(h)
// Did this code successfully run on Leetcode : yes
public ListNode reverseList(ListNode head) {
return helper(head);
}
public ListNode helper(ListNode root) {
if (root == null || root.next == null) return root;

ListNode head = helper(root.next);
root.next.next = root;
root.next = null;

return head;

}
}