Insert a node at the head of a linked list

Sort by

recency

|

970 Discussions

|

  • + 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

    Simple Solution

    C++

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    class Node {
        public:
        int data;
        Node* next;
        
        Node(int data) {
            this->data = data;
            this->next = NULL;
        }
    };
    
    class LinkedList {
        public:
        Node* head;
        
        LinkedList() {
            head = NULL;
        }
        
        void insertHead(int val) {
            Node * node = new Node(val);
            node->next = head;
            head = node;
        }
    };
    
    int main() {
        int val, n;
        cin >> n;
        LinkedList l = LinkedList(); 
        for (int i = 0; i < n; i++) {
            cin >> val;
            l.insertHead(val);
        } 
        
        Node* current = l.head;
        while(current) {
            cout << current->data << endl;
            current = current->next;
        }
        
        return 0;
    }
    

    Java

    import java.io.*;
    import java.util.*;
    
    class Node {
        int data;
        Node next;
        
        public Node(int data) {
            this.data = data;
        }
    }
    
    class LinkedList {
        Node head;
        
        public LinkedList() {
            this.head = null;
        }
        
        public void insertHead(int val) {
            Node node = new Node(val);
            node.next = head;
            head = node;
        }
    }
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            LinkedList l = new LinkedList();
            
            for (int i = 0; i < n; i++) {
                int val = sc.nextInt();
                l.insertHead(val);
            }
            
            Node current = l.head;
            while(current != null) {
                System.out.println(current.data);
                current = current.next;
            }
        }
    }
    
  • + 0 comments

    def insertNodeAtHead(llist, data): newnode = SinglyLinkedListNode(data) newnode.next = llist return newnode

  • + 0 comments

    It looks like there is a problem with the c# solution. I am getting compilation error in the pre-writtern class

  • + 0 comments

    The given C# classes do not compile. This needs to be fixed.