-
Notifications
You must be signed in to change notification settings - Fork 53
/
LinkedListInsertion.java
54 lines (41 loc) · 1.2 KB
/
LinkedListInsertion.java
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
54
package Java_DSA.Problems.Arrays;
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
public class LinkedListInsertion {
// Function to insert a new node at the beginning of the
// list
public static Node insertAtFront(Node head,
int new_data) {
// Create a new node with the given data
Node new_node = new Node(new_data);
// Make the next of the new node point to the
// current head
new_node.next = head;
// Return the new node as the new head of the list
return new_node;
}
public static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(" " + curr.data);
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create the linked list 2->3->4->5
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
int data = 1;
head = insertAtFront(head, data);
printList(head);
}
}