## DEV Community

Prashant Mishra

Posted on

TC: O(N)

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
ListNode pre = null;
ListNode next = current.next;
while(current!= null){
current.next = pre;
pre = current;
current = next;
if(next!= null) next = next.next;
}
return pre;
}
}
``````
``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
``````

Delete nth node from the back of the linkedlist

TC:O(N)

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// we will use fast and slow pointers for solving this problem
//for avoiding edge case if there is only one node in the linkedList
ListNode start = new ListNode();
start.next = head; // by this way we are ensuring that length of the list is atleast 2
ListNode fast = start;
ListNode slow = start;
for(int i =1;i<=n;++i){
fast =fast.next;
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return start.next;
}
}
``````

Merge to sorted list
TC: `O(n)` ,where `n` is `min(len(list1),len(list2))`

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode temp = new ListNode(0);
ListNode current = temp;
while(l1!=null && l2 != null){
if(l1.val < l2.val){
current.next = l1;
current = l1;
l1 = l1.next;
}
else {
current.next = l2;
current  = l2;
l2  = l2.next;
}
}
if(l1==null) current.next = l2;
else current.next = l1;
return temp.next;
}
}
``````