-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListRemoveAndAdd.java
More file actions
38 lines (30 loc) · 1.19 KB
/
LinkedListRemoveAndAdd.java
File metadata and controls
38 lines (30 loc) · 1.19 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
import java.util.LinkedList;
public class LinkedListRemoveAndAdd {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> animals = new LinkedList<>();
// Add elements to the LinkedList
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
// Print the LinkedList
System.out.println("Initial LinkedList: " + animals);
// Add an element at the beginning
animals.addFirst("Horse");
System.out.println("LinkedList after addFirst(): " + animals);
// Add an element at the end
animals.addLast("Zebra");
System.out.println("LinkedList after addLast(): " + animals);
// Remove the first element
animals.removeFirst();
System.out.println("LinkedList after removeFirst(): " + animals);
// Remove the last element
animals.removeLast();
System.out.println("LinkedList after removeLast(): " + animals);
// Iterate over the LinkedList using for-each loop
System.out.println("Accessing linked list elements:");
for (String animal : animals) {
System.out.print(animal + ", ");
}
}
}