Insert a node at the head of a linked list

Sort by

recency

|

985 Discussions

|

  • + 0 comments

    My Java solution with o(1) time complexity and o(1) space complexity:

    static SinglyLinkedListNode insertNodeAtHead(SinglyLinkedListNode llist, int data) {
            SinglyLinkedListNode newHead = new SinglyLinkedListNode(data);
            newHead.next = llist;
            return newHead;
        }
    
  • + 0 comments

    python 3

    def insertNodeAtHead(llist, data):
        new_node = SinglyLinkedListNode(node_data=data)
        if llist is None:
            return new_node
        else:
            new_node.next = llist
            return new_node
    
  • + 0 comments

    Here is my c++ solution you watch vide explanation here : https://youtu.be/COnfpdhOlN8

    SinglyLinkedListNode* insertNodeAtHead(SinglyLinkedListNode* llist, int data) {
       SinglyLinkedListNode* new_node = new SinglyLinkedListNode(data);
       new_node -> next = llist;
       return new_node;
    }
    
  • + 0 comments

    Java Solution

    static SinglyLinkedListNode insertNodeAtHead(SinglyLinkedListNode llist, int data) { SinglyLinkedListNode node = new SinglyLinkedListNode(data); if (llist != null){ node.next = llist; } llist = node; return llist; }

  • + 0 comments

    Just a warning to anyone writing this in C# c sharp: there is an error in the main function that makes solving this problem using C# impossible.

    PrintSinglyLinkedList(llist->head, "\n", textWriter);

    should be

    PrintSinglyLinkedList(llist.head, "\n", textWriter);