Java设计一个顺序表,类成员函数包括插入,删除,取数据元素,是否空,并设计测试主函数验证类成员函数正确性
时间: 2024-10-28 22:10:35 浏览: 19
在Java中,我们可以设计一个名为`LinkedList`的简单顺序表类,它包含插入、删除、获取元素以及检查是否为空的功能。下面是一个示例实现:
```java
import java.util.LinkedList;
class LinkedListNode {
int data;
LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
private LinkedListNode head;
// 插入元素
public void insertAtEnd(int data) {
LinkedListNode newNode = new LinkedListNode(data);
if (head == null) {
head = newNode;
} else {
LinkedListNode temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
// 删除元素
public boolean deleteElement(int key) {
if (head == null) {
return false;
}
if (head.data == key) {
head = head.next;
return true;
}
LinkedListNode prev = head;
LinkedListNode curr = head.next;
while (curr != null) {
if (curr.data == key) {
prev.next = curr.next;
return true;
}
prev = curr;
curr = curr.next;
}
return false;
}
// 取数据元素
public int get(int index) {
if (index < 0 || index >= size()) {
throw new IllegalArgumentException("Index out of range");
}
LinkedListNode node = head;
for (int i = 0; i < index; i++) {
node = node.next;
}
return node.data;
}
// 检查是否为空
public boolean isEmpty() {
return head == null;
}
// 计算列表长度
private int size() {
int count = 0;
LinkedListNode temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
// 主函数进行测试
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtEnd(3);
System.out.println("Is the list empty? " + list.isEmpty()); // 应该打印false
System.out.println("Get element at index 0: " + list.get(0)); // 应该打印1
System.out.println("Delete element 2: " + list.deleteElement(2)); // 应该打印true
System.out.println("After deletion, is element 2 still present? " + list.deleteElement(2)); // 应该打印false
list.printList(); // 打印剩余的元素
}
// 打印链表
private void printList() {
LinkedListNode temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}
}
```
在`main`函数中,我们测试了插入、删除、获取和判断空的操作。你可以运行这个代码来看看是否实现了预期的行为。
阅读全文