public class ArrayExample {
public static void main(String[] args) {
// 创建一个整型数组
int[] array = new int[5];
// 初始化数组元素
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
}
// 访问数组元素并打印
for (int i = 0; i < array.length; i++) {
System.out.println("数组元素 " + i + ": " + array[i]);
}
}
}
链表
由节点组成,每个节点包含数据和指向下一个节点的指针。
分为单向链表和双向链表。
灵活插入和删除元素,但访问元素需要遍历。
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class LinkedListExample {
public static void main(String[] args) {
// 创建链表节点
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
// 遍历链表并打印节点值
ListNode current = head;
while (current != null) {
System.out.println("节点值: " + current.val);
current = current.next;
}
}
}
双向链表
// 双向链表节点类
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
// 双向链表类
class DoublyLinkedList {
Node head;
Node tail;
public DoublyLinkedList() {
this.head = null;
this.tail = null;
}
// 在链表末尾添加节点
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
// 在链表头部添加节点
public void prepend(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
}
栈
后进先出 (LIFO) 的数据结构。
只能在栈顶进行插入和删除操作。
常用于表达式求值、函数调用等。
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);
// 弹出栈顶元素并打印
while (!stack.isEmpty()) {
System.out.println("栈顶元素: " + stack.pop());
}
}
}
队列
先进先出 (FIFO) 的数据结构。
可以在队列的两端进行插入和删除操作。
常用于广度优先搜索、缓冲等。
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
// 将元素添加到队列
queue.add(1);
queue.add(2);
queue.add(3);
// 从队列中移除元素并打印
while (!queue.isEmpty()) {
System.out.println("移除队列元素: " + queue.remove());
}
}
}