/**
* @author Administrator 单向链表
* @param <E>
*/
public class Link<E> {
private Node<E> first;// 头节点
private Node<E> last;// 末尾节点
private int size;// 链表的长度
private static class Node<E> {
private E item;
private Node next;
public Node(E element, Node<E> next) {
this.item = element;
this.next = next;
}
}
// 向表尾添加元素
public boolean add(E e) {
final Node<E> oldLast = last;
final Node<E> newNode = new Node<>(e, null);
last = newNode;
if (first == null) {
this.first = newNode;
} else {
oldLast.next = newNode;
}
size++;
return true;
}
// 向头部添加元素
public boolean addFirst(E e) {
final Node<E> oldFirst = first;
final Node<E> newNode = new Node<>(e, null);
first = newNode;
if (first == null) {
this.first = newNode;
} else {
first.next = oldFirst;
}
size++;
return true;
}
// 在指定的位置插入元素
public void add(int index, E e) {
check(index);
final Node<E> newNode = new Node<>(e, null);
Node<E> x = first;
if (index == 0) {
first = newNode;
} else {
index = index - 1;// 查找第i-1个元素。前一个元素
for (int i = 1; i < index; i++) {
x.next = x;
}
newNode.next = x.next;
x.next = newNode;
}
size++;
}
/**
* @param index
* 检查索引是否合法
*/
private void check(int index) {
if (index < 0 || index >= size) {
System.out.println("插入位置不合法");
return;
}
}
// 删除元素
@SuppressWarnings("unchecked")
public void remove(int index) {
check(index);
Node<E> x = first;
if (index == 0) {
first = first.next;
} else {
index = index - 1;
for (int i = 0; i < index; i++) {
x = x.next;
}
Node<E> r = x.next;// 要被删除的节点
x.next = r.next;// 空出当前节点
}
size--;
}
@SuppressWarnings("unchecked")
public E get(int index) {
check(index);
Node<E> x = first;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x.item;
}
// 转化为数组
public Object[] toArray() {
// 创建一个一样大小的数组
Object[] objs = new Object[size];
int i = 0;
for (Node<E> f = first; f != null; f = f.next) {
objs[i++] = f;
return objs;
}
return null;
}
public int size() {
return this.size;
}
public void rev() {
Node<E> pre = null;// 上一个节点
Node<E> cur = pre.next;// 当前节点
for (Node<E> x = first; x != null; x = x.next) {
pre = cur.next;
}
}
public static void main(String[] args) {
Link<Integer> l = new Link<Integer>();
l.add(1);
l.add(2);
l.addFirst(3);
l.add(1, 4);
for (int i = 0; i < l.size; i++) {
System.out.println(l.get(i));
}
System.out.println("----------");
System.out.println(l.toArray());
System.out.println(l.size());
}
}
链式存储结构之单向链表
最新推荐文章于 2025-02-18 21:32:40 发布