-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathinsertathead.java
More file actions
53 lines (44 loc) · 1.41 KB
/
insertathead.java
File metadata and controls
53 lines (44 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;
// Node class to represent a linked list node
class Node {
public int data;
public Node next;
// Constructor with both data and next node
public Node(int data1, Node next1) {
data = data1;
next = next1;
}
// Constructor with only data (assuming next is initially null)
public Node(int data1) {
data = data1;
next = null;
}
}
public class InsertAtHead {
// Function to print the linked list
public static void printLL(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
// Function to insert a new node at the head of the linked list
public static Node insertHead(Node head, int val) {
Node temp = new Node(val, head);
return temp;
}
public static void main(String[] args) {
// Sample array and value for insertion
List<Integer> arr = Arrays.asList(12, 8, 5, 7);
int val = 100;
// Creating a linked list with initial elements from the array
Node head = new Node(arr.get(0));
head.next = new Node(arr.get(1));
head.next.next = new Node(arr.get(2));
head.next.next.next = new Node(arr.get(3));
// Inserting a new node at the head of the linked list
head = insertHead(head, val);
// Printing the linked list
printLL(head);
}
}