The code demonstrates how to use the push and pop methods of LinkedList in Java to add items to the beginning of the list and remove items from the beginning of the list, respectively.
In the Pop_Items class, a LinkedList object named bk is created with a type parameter
The System.out.println statements are used to print the items removed from the bk list using the pop method. The pop method removes and returns the first item (i.e., the item at the beginning) of the list. Note that the items are printed in the reverse order they were added, since pop removes items from the beginning of the list. If the list is empty, pop returns null.
Please note that using push and pop methods on a LinkedList can result in poor performance for large lists, as adding or removing items from the beginning of the list requires shifting all the subsequent items, resulting in an O(n) time complexity operation. For better performance, consider using a Deque implementation, such as ArrayDeque, which provides efficient addFirst, removeFirst, addLast, and removeLast methods to add and remove items from both ends of the list in constant time.
import java.util.LinkedList; public class Pop_Items { public static void main(String[] args) { LinkedList <String> bk = new LinkedList <String> (); bk.push("CPP"); bk.push("JAVA"); bk.push("PYTHON"); bk.push("C"); bk.push("RUBY"); bk.push("C#.NET"); System.out.println(bk.pop()); System.out.println(bk.pop()); System.out.println(bk.pop()); System.out.println(bk.pop()); System.out.println(bk.pop()); System.out.println(bk.pop()); } }
C#.NET RUBY C PYTHON JAVA CPP
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions