4-Array List and Linked List-21!12!2024
4-Array List and Linked List-21!12!2024
IN
JAVA
LINKED –LIST
KEY–NOTE TO LINKED LIST
Parameters:
// Creating a LinkedList
LinkedList<String> friends = new LinkedList<>();
// Adding new elements to the end of the LinkedList using add() method.
friends.add("Rajeev");
friends.add("John");
friends.add("David”);
friends.add("Chris");
//Adding an element at the beginning of the LinkedList
friends.addFirst("Steve");
System.out.println("After addFirst(\"Steve\") : " + friends);
addLast
Parameters:
e - the element to add
LOGIC
// Creating a LinkedList
LinkedList<String> friends = new LinkedList<>();
// Adding new elements to the end of the LinkedList using add() method.
friends.add("Rajeev");
friends.add("John");
friends.add("David”);
friends.add("Chris");
// Adding an element at the end of the LinkedList (This method is
equivalent to the add() method)
friends.addLast("Jennifer");
System.out.println("After addLast(\"Jennifer\") : " + friends);
offer
// Declaring a LinkedList
LinkedList list = new LinkedList();
// adding elements
list.add(“RAJ”);
list.add(4);
list.add(“Hemanth”);
list.add(8);
// printing the list
System.out.println("The initial Linked list is : " + list);
// offering a new element
// adds element at tail.
list.offer(“Astha”);
// printing the new list
System.out.println("LinkedList after insertion using offer() : " +
list);
peek
public E peek()
Retrieves, but does not remove, the last element of this list, or returns null
if this list is empty
Returns: the last element of this list, or null if this list is empty
LOGIC
// declaring a LinkedList
LinkedList list = new LinkedList();
// adding elements
list.add("GeM");
list.add(4);
list.add("GREY");
list.add("8");
// printing the list
System.out.println("The initial list is :" + list);