在Java语言中,如何使用Eclipse开发工具实现线性表的顺序存储和链式存储?请结合教学资源《Java数据结构:线性表的教学设计与学习目标》给出示例代码。
时间: 2024-10-31 12:16:08 浏览: 18
在Java语言中,实现线性表的顺序存储和链式存储需要分别构建顺序表类和链表类。顺序表基于数组实现,而链表则基于节点的引用关系。以下是具体的示例代码:
参考资源链接:[Java数据结构:线性表的教学设计与学习目标](https://wenku.csdn.net/doc/1gt8g8fehx?spm=1055.2569.3001.10343)
顺序表的实现(顺序存储结构):
```java
import java.util.Arrays;
class SequentialList {
private int[] data;
private int size;
public SequentialList(int capacity) {
data = new int[capacity];
size = 0;
}
public void add(int index, int element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (size == data.length) {
resize(2 * data.length);
}
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = element;
size++;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return data[index];
}
private void resize(int newCapacity) {
data = Arrays.copyOf(data, newCapacity);
}
}
```
单链表的实现(链式存储结构):
```java
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class LinkedList {
private ListNode head;
public void addFirst(int element) {
ListNode newNode = new ListNode(element);
newNode.next = head;
head = newNode;
}
public void removeFirst() {
if (head != null) {
head = head.next;
}
}
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.val +
参考资源链接:[Java数据结构:线性表的教学设计与学习目标](https://wenku.csdn.net/doc/1gt8g8fehx?spm=1055.2569.3001.10343)
阅读全文