Java函数实现数据结构中的栈、队列和链表。
发布时间:2023-07-02 17:19:16
栈、队列和链表是常用的数据结构,它们在编程中有着重要的作用。下面我将用Java语言实现这几个数据结构。
1. 栈(Stack)是一种后进先出(LIFO)的数据结构。在Java中,我们可以使用LinkedList或者ArrayDeque来实现栈。
import java.util.LinkedList;
import java.util.Deque;
public class Stack<E> {
private Deque<E> stack;
public Stack() {
stack = new LinkedList<>();
}
public void push(E item) {
stack.push(item);
}
public E pop() {
return stack.pop();
}
public E peek() {
return stack.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
public int size() {
return stack.size();
}
}
2. 队列(Queue)是一种先进先出(FIFO)的数据结构。在Java中,我们可以使用LinkedList或者ArrayDeque来实现队列。
import java.util.LinkedList;
import java.util.Queue;
public class Queue<E> {
private Queue<E> queue;
public Queue() {
queue = new LinkedList<>();
}
public void enqueue(E item) {
queue.add(item);
}
public E dequeue() {
return queue.poll();
}
public E peek() {
return queue.peek();
}
public boolean isEmpty() {
return queue.isEmpty();
}
public int size() {
return queue.size();
}
}
3. 链表(LinkedList)是一种由节点组成的线性数据结构,每个节点包含一个数据元素和一个指向下一个节点的指针。在Java中,我们可以使用自定义的LinkedList类来实现链表。
public class LinkedList<E> {
private Node<E> head;
private int size;
private static class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this.data = data;
this.next = null;
}
}
public LinkedList() {
head = null;
size = 0;
}
public void add(E item) {
Node<E> newNode = new Node<>(item);
if (head == null) {
head = newNode;
} else {
Node<E> current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
public void remove(E item) {
if (head == null) {
return;
}
if (head.data.equals(item)) {
head = head.next;
size--;
return;
}
Node<E> current = head;
while (current.next != null) {
if (current.next.data.equals(item)) {
current.next = current.next.next;
size--;
return;
}
current = current.next;
}
}
public boolean contains(E item) {
Node<E> current = head;
while (current != null) {
if (current.data.equals(item)) {
return true;
}
current = current.next;
}
return false;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
}
以上是使用Java实现栈、队列和链表的代码。这些数据结构在实际编程中非常常用,可以用来解决各种问题。
