Skip to content

Commit c5c8cc3

Browse files
authored
Added solutions for 2 linked list problems (#39)
1 parent 73d757a commit c5c8cc3

File tree

3 files changed

+161
-81
lines changed

3 files changed

+161
-81
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public TreeNode sortedArrayToBST(int[] nums) {
18+
// use merge sort strategy to convert sorted list to BST
19+
return buildTree(0, nums.length-1, nums);
20+
}
21+
22+
public TreeNode buildTree(int l, int r, int nums[]){
23+
// base case
24+
if(l>r) return null;
25+
// get mid of the whole index of the current list
26+
int mid = (l+r)/2;
27+
// create a node for mid of current subarray
28+
TreeNode node = new TreeNode(nums[mid]);
29+
// recurse for getting the left subtree
30+
node.left = buildTree(l, mid-1, nums);
31+
// recurse for getting the right subtree
32+
node.right = buildTree(mid+1, r, nums);
33+
// return the node
34+
return node;
35+
}
36+
37+
}
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode removeNthFromEnd(ListNode head, int n) {
13+
ListNode slow = head, fast = head, prev = null;
14+
// move one ptr such that it points to nth node from start of Linked List
15+
while(n-->1)
16+
fast = fast.next;
17+
18+
// now move the second ptr as long as first ptr doesn't point to last node
19+
while(fast.next!=null){
20+
prev = slow;
21+
slow = slow.next;
22+
fast = fast.next;
23+
}
24+
25+
// if the nth node from end is the start node of list
26+
if(prev==null)
27+
head = head.next;
28+
else
29+
prev.next = slow.next;
30+
31+
return head;
32+
}
33+
}

0 commit comments

Comments
 (0)