Java中的LinkedList removeLast()方法
Java.util.LinkedList.removeLast() 方法用于从 LinkedList 中删除最后一个元素。此方法还会在删除元素后返回该元素。
句法:
LinkedList.removeLast()
参数:此函数不带任何参数。
返回值:该方法返回最后一个元素或存在于列表尾部的元素。
下面的程序说明了Java.util.LinkedList.removeLast() 方法:
Java
// Java code to illustrate removeLast()
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[])
{
// Creating an empty LinkedList
LinkedList list = new LinkedList();
// Use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Displaying the list
System.out.println("LinkedList:" + list);
// Remove the tail using removeLast()
System.out.println("The last element is removed: " + list.removeLast());
// Displaying the final list
System.out.println("Final LinkedList:" + list);
// Remove the tail using removeLast()
System.out.println("The last element is removed: " + list.removeLast());
// Displaying the final list
System.out.println("Final LinkedList:" + list);
}
}
输出:
LinkedList:[Geeks, for, Geeks, 10, 20]
The last element is removed: 20
Final LinkedList:[Geeks, for, Geeks, 10]
The last element is removed: 10
Final LinkedList:[Geeks, for, Geeks]
removeLast() 的时间复杂度:O(1)