Java实现栈,队列,数组,链表数据结构
时间: 2024-02-07 07:41:03 浏览: 80
数据结构-简单介绍
Java实现栈的代码:
```java
public class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full!");
return;
}
stackArray[++top] = value;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty!");
return -1;
}
return stackArray[top--];
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty!");
return -1;
}
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
}
```
Java实现队列的代码:
```java
public class Queue {
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
public Queue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(int value) {
if (isFull()) {
System.out.println("Queue is full!");
return;
}
if (rear == maxSize - 1) {
rear = -1;
}
queueArray[++rear] = value;
nItems++;
}
public int remove() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return -1;
}
int temp = queueArray[front++];
if (front == maxSize) {
front = 0;
}
nItems--;
return temp;
}
public int peekFront() {
if (isEmpty()) {
System.out.println("Queue is empty!");
return -1;
}
return queueArray[front];
}
public boolean isEmpty() {
return (nItems == 0);
}
public boolean isFull() {
return (nItems == maxSize);
}
}
```
Java实现数组的代码:
```java
public class MyArray {
private int[] array;
private int length;
public MyArray(int[] arr) {
array = arr;
length = arr.length;
}
public int get(int index) {
if (index < 0 || index >= length) {
System.out.println("Invalid index!");
return -1;
}
return array[index];
}
public void set(int index, int value) {
if (index < 0 || index >= length) {
System.out.println("Invalid index!");
return;
}
array[index] = value;
}
public int length() {
return length;
}
public void display() {
for (int i = 0; i < length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
```
Java实现链表的代码:
```java
public class Node {
public int value;
public Node next;
public Node(int val) {
value = val;
next = null;
}
}
public class LinkedList {
private Node head;
public LinkedList() {
head = null;
}
public void insertFirst(int value) {
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
}
public Node deleteFirst() {
if (isEmpty()) {
System.out.println("List is empty!");
return null;
}
Node temp = head;
head = head.next;
return temp;
}
public boolean isEmpty() {
return (head == null);
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.value + " ");
current = current.next;
}
System.out.println();
}
}
```
阅读全文