-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion of Single Link List at End
67 lines (54 loc) · 1.71 KB
/
Insertion of Single Link List at End
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
package DataS;
// Define the Node class
class Node {
int data;
Node next;
// Constructor to initialize a new node with given data
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Define the SingleLinkedList class
public class Single_Link_End {
private Node head; // Head of the linked list
// Constructor to initialize an empty linked list
public Single_Link_End() {
this.head = null;
}
// Method to insert a node at the end of the linked list
public void insertAtEnd(int data) {
Node newNode = new Node(data); // Create a new node with the given data
// If the linked list is empty, make the new node as head
if (head == null) {
head = newNode;
return;
}
// Traverse to the last node
Node last = head;
while (last.next != null) {
last = last.next;
}
// Insert the new node at the end
last.next = newNode;
}
// Method to print the linked list
public void printList() {
Node current = head; // Start from the head node
System.out.print("Linked List: ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
// Main method to test the implementation
public static void main(String[] args) {
Single_Link_End list = new Single_Link_End(); // Create an instance of Single_Link_End
list.insertAtEnd(10);
list.insertAtEnd(22);
list.insertAtEnd(33);
// Print the linked list
list.printList();
}
}