使用java实现顺序表和链表 从0到9
时间: 2024-09-14 09:10:21 浏览: 44
在Java中,我们可以使用数组(顺序表)和单链表来存储数字序列,比如从0到9。下面我会分别简要地介绍这两种数据结构:
**1. 数组(顺序表)实现**:
```java
public class ArrayList {
private int[] elements;
private int size;
public ArrayList(int capacity) {
elements = new int[capacity];
size = 0;
}
// 添加元素至末尾
public void add(int num) {
if (size == elements.length) {
resize(size * 2);
}
elements[size++] = num;
}
// 打印从0到9
public void print() {
for (int i = 0; i < size; i++) {
System.out.print(elements[i] + " ");
}
System.out.println();
}
// 私有方法调整数组大小
private void resize(int newSize) {
int[] newArray = new int[newSize];
System.arraycopy(elements, 0, newArray, 0, size);
elements = newArray;
}
}
```
**2. 链表(单链表)实现**:
```java
public class LinkedListNode {
int value;
LinkedListNode next;
public LinkedListNode(int val) {
value = val;
}
}
public class SinglyLinkedList {
private LinkedListNode head;
// 插入节点
public void add(int num) {
LinkedListNode newNode = new LinkedListNode(num);
if (head == null) {
head = newNode;
} else {
LinkedListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 打印从0到9
public void print() {
LinkedListNode temp = head;
while (temp != null) {
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
}
```
阅读全文