diff --git a/Problem49.java b/Problem49.java new file mode 100644 index 00000000..d3f1bcff --- /dev/null +++ b/Problem49.java @@ -0,0 +1,17 @@ +// Time Complexity : O(N) +// Space Complexity : O(1) + +class Solution { + public ListNode reverseList(ListNode head) { + ListNode curr = head; + ListNode prev = null; + + while(curr != null) { + ListNode temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + return prev; + } +} \ No newline at end of file diff --git a/Problem50.java b/Problem50.java new file mode 100644 index 00000000..412cbcfb --- /dev/null +++ b/Problem50.java @@ -0,0 +1,29 @@ +// Time Complexity : O(N) +// Space Complexity : O(1) + +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode (-1); + dummy.next = head; + int count = 0; + + ListNode slow = dummy; + ListNode fast = dummy; + + while (count <= n) { + fast = fast.next; + count++; + } + + while (fast != null){ + slow = slow.next; + fast = fast.next; + } + + ListNode temp = slow.next; + slow.next = slow.next.next; + temp.next = null; + + return dummy.next; + } +} \ No newline at end of file diff --git a/Problem51.java b/Problem51.java new file mode 100644 index 00000000..ced04492 --- /dev/null +++ b/Problem51.java @@ -0,0 +1,31 @@ +// Time Complexity : O(N) +// Space Complexity : O(1) + +public class Solution { + public ListNode detectCycle(ListNode head) { + if(head == null) return null; + ListNode slow = head; + ListNode fast = head; + boolean flag = false; + + while(fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + flag = true; + break; + } + } + + if (!flag) return null; + + slow = head; + while(slow != fast){ + slow = slow.next; + fast = fast.next; + } + + return slow; + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index f5c45b5f..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach \ No newline at end of file