java实现线性表
时间: 2023-08-16 22:04:21 浏览: 37
Java中实现线性表最常用的方式是使用数组或者链表。
1. 使用数组实现线性表:
```java
public class ArrayList {
private Object[] array;
private int size;
public ArrayList(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be greater than 0!");
}
array = new Object[capacity];
size = 0;
}
public ArrayList() {
this(10);
}
public void add(Object obj) {
if (size == array.length) {
Object[] newArray = new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[size] = obj;
size++;
}
public Object get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
return array[index];
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
array[size] = null;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
}
```
2. 使用链表实现线性表:
```java
public class LinkedList {
private Node head;
private int size;
public LinkedList() {
head = null;
size = 0;
}
public void add(Object obj) {
Node newNode = new Node(obj, null);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
size++;
}
public Object get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
Node temp = head;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp.data;
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
if (index == 0) {
head = head.next;
} else {
Node temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
}
size--;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
private static class Node {
Object data;
Node next;
Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
}
```