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
44 changes: 44 additions & 0 deletions DetectCycle-2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(1)

public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
boolean flag = false;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
flag = true;
break;
}

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

// TimeComplexity: O(n)
// SpaceComplexity: O(n)
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while(head!=null) {
if(set.contains(head)) {
return head;
}
set.add(head);
head = head.next;
}
return null;
}
}
57 changes: 57 additions & 0 deletions remove-nth-node-from-end-of-linked-list.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// TimeComplexity: O(n)
// SpaceComplexity: O(1)
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1, head);
ListNode slow = dummy;
ListNode fast = dummy;
int i =0;
while(i<=n) {
fast = fast.next;
i++;
}
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
ListNode temp = slow.next;
slow.next = slow.next.next;
temp.next = null;
return dummy.next;
}
}


// TimeComplexity: O(2n)
// SpaceComplexity: O(1)

class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = head;
int m=0;
while(first!=null) {
m++;
first = first.next;
}
System.out.println(m);
int k = m-n;
if(k==0) {
ListNode temp2 = head;
head= head.next;
temp2.next = null;
return head;
}
ListNode second = head;
for(int i=0; i<k-1; i++){
System.out.println(second.val);
second= second.next;
}

ListNode temp = second.next;
second.next = second.next.next;
temp.next = null;

return head;

}
}
42 changes: 42 additions & 0 deletions reverse-linked-list.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Solution -1

// TimeComplexity: O(n)
// SpaceComplexity: O(1)

class Solution {
ListNode output;
public ListNode reverseList(ListNode head) {
helper(head);
return output;
}

private void helper(ListNode head) {
if(head == null || head.next ==null) {
output = head;
return;
}
helper(head.next);
head.next.next = head;
head.next =null;
return;
}
}

// Solution -2

// TimeComplexity: O(n)
// SpaceComplexity: O(1)

class Solution {
public ListNode reverseList(ListNode head) {
ListNode output = null;
while(head!=null) {
ListNode temp = head;
head= head.next;
temp.next = output;
output = temp;
}
return output;

}
}