原文: https://beginnersbook.com/2014/08/linkedlist-push-and-pop-methods-java/

描述

用于演示LinkedList上的推送和弹出操作的程序。

LinkedList.push(E e)

public void push(E e):将元素插入列表的前面。

示例:

  1. import java.util.LinkedList;
  2. class LinkedListExample {
  3. public static void main(String[] args) {
  4. // Create a LinkedList of Strings
  5. LinkedList<String> list = new LinkedList<String>();
  6. // Add few Elements
  7. list.add("Jack");
  8. list.add("Robert");
  9. list.add("Chaitanya");
  10. list.add("kate");
  11. // Display LinkList elements
  12. System.out.println("LinkedList contains: "+list);
  13. // push Element the list
  14. list.push("NEW ELEMENT");
  15. // Display after push operation
  16. System.out.println("LinkedList contains: "+list);
  17. }
  18. }

输出:

  1. LinkedList contains: [Jack, Robert, Chaitanya, kate]
  2. LinkedList contains: [NEW ELEMENT, Jack, Robert, Chaitanya, kate]

LinkedList.pop()

public E pop():删除并返回列表的第一个元素。

示例:

  1. import java.util.LinkedList;
  2. class LinkedListPopDemo{
  3. public static void main(String[] args) {
  4. // Create a LinkedList of Strings
  5. LinkedList<String> list = new LinkedList<String>();
  6. // Add few Elements
  7. list.add("Jack");
  8. list.add("Robert");
  9. list.add("Chaitanya");
  10. list.add("kate");
  11. // Display LinkList elements
  12. System.out.println("LinkedList before: "+list);
  13. // pop Element from list and display it
  14. System.out.println("Element removed: "+list.pop());
  15. // Display after pop operation
  16. System.out.println("LinkedList after: "+list);
  17. }
  18. }

输出:

  1. LinkedList before: [Jack, Robert, Chaitanya, kate]
  2. Element removed: Jack
  3. LinkedList after: [Robert, Chaitanya, kate]