java数据结构单链表adt
时间: 2023-12-12 14:03:59 浏览: 91
单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的引用。单链表的优点是插入和删除操作的时间复杂度为O(1),但是访问操作的时间复杂度为O(n)。下面是Java实现单链表ADT的示例代码:
```java
public class LinkedList {
private Node head;
private int size;
private class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public LinkedList() {
head = null;
size = 0;
}
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
size++;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
head = head.next;
} else {
Node current = head;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
size--;
}
public int size() {
return size;
}
}
```
阅读全文