-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeletion of Single Link List at Beginning
More file actions
75 lines (61 loc) · 2.2 KB
/
Deletion of Single Link List at Beginning
File metadata and controls
75 lines (61 loc) · 2.2 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package DataS;
public class Deletion_Single_Link_Beginning {
// Node class representing each element of the linked list
static class Node {
int data; // Data stored in the node
Node next; // Pointer to the next node in the list
// Constructor to create a new node
Node(int data) {
this.data = data;
this.next = null;
}
}
Node head; // Head of the list
// Constructor to initialize an empty list
public Deletion_Single_Link_Beginning() {
head = null;
}
// Function to insert a node at the beginning of the list
public void insertAtBeginning(int data) {
// Create a new node with the given data
Node newNode = new Node(data);
// Point the new node's next to the current head
newNode.next = head;
// Update head to the new node
head = newNode;
}
// Function to delete a node from the beginning of the list
public void deleteAtBeginning() {
if (head == null) {
System.out.println("List is empty. Nothing to delete.");
return;
}
head = head.next; // Move head to the next node
}
// Function to print the linked list
public void printList() {
Node current = head; // Start from the head
// Traverse the list until the end
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("NULL");
}
// Main method to demonstrate the insertion and deletion
public static void main(String[] args) {
Deletion_Single_Link_Beginning list = new Deletion_Single_Link_Beginning();
// Insert nodes at the beginning
list.insertAtBeginning(10);
list.insertAtBeginning(20);
list.insertAtBeginning(30);
// Print the linked list
System.out.println("Linked List after insertions:");
list.printList();
// Delete node from the beginning
list.deleteAtBeginning();
// Print the linked list after deletion
System.out.println("Linked List after deletion at beginning:");
list.printList();
}
}