Sort by

recency

|

833 Discussions

|

  • + 0 comments

    if(llist == null) return null;

        if(position == 0){
            SinglyLinkedListNode newHead = llist.next;
            llist.next = null;
            return newHead;
        }
    
        SinglyLinkedListNode curr = llist;
        for(int i = 0; i < position; i++){
            if(i == position - 1){
                curr.next = curr.next.next;
            } else curr = curr.next;
        }
        return llist;
    
  • + 0 comments

    Java 8 Solution:

    public static SinglyLinkedListNode deleteNode(SinglyLinkedListNode llist, int position) {
            if (position == 0) {
                llist = llist.next;
                return llist;
            }
            SinglyLinkedListNode current = llist;
            llist = current;
            
            int index = 0;
            while (index < position - 1) {
                current = current.next;
                index++;
            }
            current.next = current.next.next;
            return llist;
        }
    
  • + 0 comments

    Python Solution:

    def deleteNode(llist, position):

    cur = llist
    if position == 0:
        return llist.next
    else:
    
        for i in range(position):
            prev = cur
            cur = cur.next
        prev.next = cur.next
    return llist
    
  • + 0 comments

    My Java solution with linear time complexity and constant space complexity:

    public static SinglyLinkedListNode deleteNode(SinglyLinkedListNode llist, int position) {
            if(llist == null) return null;
            
            if(position == 0){
                SinglyLinkedListNode newHead = llist.next;
                llist.next = null;
                return newHead;
            }
            
            SinglyLinkedListNode curr = llist;
            for(int i = 0; i < position; i++){
                if(i == position - 1){
                    curr.next = curr.next.next;
                } else curr = curr.next;
            }
            return llist;
        }
    
  • + 0 comments

    Here is my c++ solution, you can have the video explanation here : https://youtu.be/EjWw69vLVYo

    SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* llist, int position) {
        if(position == 0) return llist->next;
        SinglyLinkedListNode* curr = llist;
        while(position - 1) {
            curr = curr -> next;
            position--;
        }
        curr->next = curr->next->next;
        return llist;
    }