用Java编写根据要求练习LinkedList方法,并提交运行结果截图 (1)基本方法:add, set, get, remove, clear, size等方法; (2)特有方法:addFirst, addLast, getFirst, getLast, removeFirst, removeLast, push, pop, clear等方法。 void push(E e):与addFirst一样,实际上它就是addFirst; E pop():与removeFirst一样,实际上它就是removeFirst; E poll():查询并移除第一个元素;
时间: 2024-04-12 10:32:04 浏览: 106
好的,以下是根据您的要求编写的LinkedList方法的示例代码:
```java
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();
// 基本方法
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
System.out.println("LinkedList: " + linkedList);
linkedList.set(1, "D");
System.out.println("LinkedList after set: " + linkedList);
String element = linkedList.get(2);
System.out.println("Element at index 2: " + element);
linkedList.remove(0);
System.out.println("LinkedList after remove: " + linkedList);
linkedList.clear();
System.out.println("LinkedList after clear: " + linkedList);
int size = linkedList.size();
System.out.println("Size of LinkedList: " + size);
// 特有方法
linkedList.addFirst("X");
System.out.println("LinkedList after addFirst: " + linkedList);
linkedList.addLast("Y");
System.out.println("LinkedList after addLast: " + linkedList);
String firstElement = linkedList.getFirst();
System.out.println("First element: " + firstElement);
String lastElement = linkedList.getLast();
System.out.println("Last element: " + lastElement);
String removedFirstElement = linkedList.removeFirst();
System.out.println("Removed first element: " + removedFirstElement);
System.out.println("LinkedList after removeFirst: " + linkedList);
String removedLastElement = linkedList.removeLast();
System.out.println("Removed last element: " + removedLastElement);
System.out.println("LinkedList after removeLast: " + linkedList);
linkedList.push("Z");
System.out.println("LinkedList after push: " + linkedList);
String poppedElement = linkedList.pop();
System.out.println("Popped element: " + poppedElement);
System.out.println("LinkedList after pop: " + linkedList);
String polledElement = linkedList.poll();
System.out.println("Polled element: " + polledElement);
System.out.println("LinkedList after poll: " + linkedList);
}
}
```
您可以将上述代码保存为.java文件并运行,然后将运行结果截图提交给我。
阅读全文