再详细一点,多一点数据结构
时间: 2023-08-13 12:08:26 浏览: 107
当谈到数据结构的Java代码实现时,还有很多其他常见的数据结构可以探索,例如栈、队列、树和图。下面我将进一步介绍这些数据结构的代码实现。
1. 栈(Stack):
栈是一种先进后出(LIFO)的数据结构。以下是使用数组实现栈的简单示例:
```java
class Stack {
private int maxSize;
private int top;
private int[] stackArray;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
}
}
public int pop() {
if (top >= 0) {
return stackArray[top--];
}
return -1;
}
public int peek() {
if (top >= 0) {
return stackArray[top];
}
return -1;
}
public boolean isEmpty() {
return (top == -1);
}
}
```
2. 队列(Queue):
队列是一种先进先出(FIFO)的数据结构。以下是使用数组实现队列的简单示例:
```java
class Queue {
private int maxSize;
private int front;
private int rear;
private int[] queueArray;
public Queue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
}
public void enqueue(int value) {
if (rear < maxSize - 1) {
queueArray[++rear] = value;
}
}
public int dequeue() {
if (front <= rear) {
return queueArray[front++];
}
return -1;
}
public int peek() {
if (front <= rear) {
return queueArray[front];
}
return -1;
}
public boolean isEmpty() {
return (front > rear);
}
}
```
3. 树(Tree):
树是一种非线性的数据结构,它由节点组成,每个节点可以有多个子节点。以下是使用链表实现二叉树的简单示例:
```java
class TreeNode {
int data;
TreeNode left;
TreeNode right;
public TreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree {
TreeNode root;
public BinaryTree() {
root = null;
}
public void insert(int data) {
root = insertNode(root, data);
}
private TreeNode insertNode(TreeNode root, int data) {
if (root == null) {
root = new TreeNode(data);
return root;
}
if (data < root.data) {
root.left = insertNode(root.left, data);
} else if (data > root.data) {
root.right = insertNode(root.right, data);
}
return root;
}
public void traverseInOrder() {
inOrder(root);
}
private void inOrder(TreeNode root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
}
```
4. 图(Graph):
图是一种由节点和边组成的非线性数据结构。以下是使用邻接矩阵表示图的简单示例:
```java
class Graph {
private int vertexCount;
private boolean[][] matrix;
public Graph(int vertexCount) {
this.vertexCount = vertexCount;
matrix = new boolean[vertexCount][vertexCount];
}
public void addEdge(int source, int destination) {
if (source >= 0 && source < vertexCount && destination >= 0 && destination < vertexCount) {
matrix[source][destination] = true;
matrix[destination][source] = true;
}
}
public void removeEdge(int source, int destination) {
if (source >= 0 && source < vertexCount && destination >= 0 && destination < vertexCount) {
matrix[source][destination] = false;
matrix[destination][source] = false;
}
}
public boolean hasEdge(int source, int destination) {
if (source >= 0 && source < vertexCount && destination >= 0 && destination < vertexCount) {
return matrix[source][destination];
}
return false;
}
}
```
这些是一些常见数据结构的Java代码实现示例。你可以根据需要进行修改和扩展,以满足特定的问题要求。希望这些示例能够帮助你更好地理解数据结构的Java代码实现。