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
37 changes: 37 additions & 0 deletions LinkedListCycleII.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes

// Use slow and fast pointers to detect whether a cycle exists.
// If no cycle is found, return null.
// Reset one pointer to the head and move both one step at a time until they meet at the cycle's starting node.

public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
boolean isCycleExists = false;

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

if(slow == fast) {
isCycleExists = true;
break;
}
}

if(!isCycleExists) {
return null;
}

slow = head;

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

return fast;
}
}
35 changes: 35 additions & 0 deletions RemoveNthNode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes

// Find the length of the linked list using a dummy node.
// Compute the position of the node to remove and traverse to its previous node.
// Skip the target node by updating the previous node's next pointer.

class RemoveNthNode {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(-1, head);

ListNode current = dummyHead;
int length = 0;

while(current != null) {
length++;
current = current.next;
}

int targetIndex = length - n + 1;
int index = 1;
current = dummyHead;
while(index < targetIndex - 1) {
current = current.next;
index++;
}
current.next = current.next.next;
if(index == 1) {
head = current.next;
}

return head;
}
}
22 changes: 22 additions & 0 deletions ReverseLinkedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes

// Traverse the linked list while maintaining previous, current, and next pointers.
// Reverse each node's next pointer to point to the previous node.
// Move the pointers forward and return the new head after the traversal completes.

class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
ListNode prev = null, current = head;

while(current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}

return prev;
}
}