You are viewing a single comment's thread. Return to all comments →
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; } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at the head of a linked list
You are viewing a single comment's thread. Return to all comments →
Simple Solution
C++
Java