Java中的常用数据结构包括栈、队列、链表等,它们是用来组织和存储数据的不同方式。下面将对这几种数据结构进行详细解释,并提供示例代码。
示例:
java复制代码
import java.util.Stack; | |
public class StackExample { | |
public static void main(String[] args) { | |
Stack<Integer> stack = new Stack<>(); | |
// 入栈操作 | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
// 查看栈顶元素 | |
System.out.println("栈顶元素:" + stack.peek()); // 输出 "3" | |
// 出栈操作 | |
int poppedElement = stack.pop(); | |
System.out.println("出栈元素:" + poppedElement); // 输出 "3" | |
System.out.println("栈顶元素:" + stack.peek()); // 输出 "2" | |
} | |
} |
示例:
java复制代码
import java.util.Queue; | |
import java.util.LinkedList; | |
public class QueueExample { | |
public static void main(String[] args) { | |
Queue<Integer> queue = new LinkedList<>(); | |
// 入队操作 | |
queue.add(1); | |
queue.add(2); | |
queue.add(3); | |
// 查看队头元素 | |
System.out.println("队头元素:" + queue.peek()); // 输出 "1" | |
// 出队操作 | |
int dequeuedElement = queue.poll(); | |
System.out.println("出队元素:" + dequeuedElement); // 输出 "1" | |
System.out.println("队头元素:" + queue.peek()); // 输出 "2" | |
} | |
} |
示例:
java复制代码
import java.util.LinkedList; | |
import java.util.ListIterator; | |
public class LinkedListExample { | |
public static void main(String[] args) { | |
LinkedList<String> linkedList = new LinkedList<>(); | |
linkedList.add("Apple"); | |
linkedList.add("Banana"); | |
linkedList.add("Orange"); | |
linkedList.add("Grape"); | |
// 使用ListIterator遍历链表(从后向前) | |
ListIterator<String> listIterator = linkedList.listIterator(linkedList.size()); | |
while (listIterator.hasPrevious()) { | |
String fruit = listIterator.previous(); | |
System.out.println(fruit); // 输出 "Grape", "Orange", "Banana", "Apple" | |
} | |
} | |
} |