这是一个简单的单向链表实现,使用泛型特性,顺序存储每个节点数据,并可获取该链表数据的数组表示形式。
编程环境: Win10、 JDK:1.7.0_21(64-bit)、 Eclipse:Version: Mars.1 Release (4.5.1)
1、代码实现
package testl.dataStructure.linkedList;
import java.util.Arrays;
/**
* 链表(非线程安全), T 表示节点中数据的类型,该链表是有序的,按照添加顺序存放节点,返回的数组元素的顺序与添加顺序一致
*/
public class LinkedList<T> {
/**
* 该链表中的第一个节点
*/
private Node<T> headNode;
/**
* 该链表中的最后一个节点
*/
private Node<T> tailNode;
/**
* 该链表中节点元素的个数
*/
private int size;
public LinkedList() {
}
/**
* 向该链表添加数据节点
*/
public void add(T data) {
if (headNode == null) {
headNode = new Node<T>(data, null);
tailNode = headNode;
} else {
Node<T> newNode = new Node<T>(data, null);
tailNode.nextNode = newNode;
tailNode = newNode;
}
size++;
}
/**
* 返回链表当前节点个数
*/
public int size() {
return size;
}
/**
* 返回链表中节点数据的数组表示形式
*/
public T[] toArray(T[] array) {
T[] newArray = Arrays.copyOf(array, size);
int indexOfArray = 0;
Node<T> itarator = headNode;
while (itarator != null && itarator.nextNode != null) {
newArray[indexOfArray++] = itarator.getData();
itarator = itarator.nextNode;
}
// 处理最后一个节点
newArray[indexOfArray] = itarator.getData();
return newArray;
}
/**
* 获取该链表的最后一个节点数据
*/
public T last() {
return tailNode.getData();
}
/**
* 获取该链表的第一个节点数据
*/
public T first() {
return headNode.getData();
}
/**
* 获取index位置的节点数据,第一个节点的index值为0
*/
public T get(int index) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException("expected: " + index + ", actual: " + (size - 1));
} else if (index == 0) {
// 第一个节点
return headNode.getData();
} else if (index == (size - 1)) {
// 最后一个节点
return tailNode.getData();
} else {
// 从第二个节点开始查找,并且忽略最后一个节点
int i = 1;
Node<T> iterator = headNode.nextNode;
while (iterator != null && iterator.nextNode != null) {
if ((i++) == index) {
break;
}
iterator = iterator.nextNode;
}
return iterator.getData();
}
}
/**
* 节点,表示链表中的一个节点元素, T 表示节点中数据的类型 。可见性:LinkedList 私有内部类,static
* 表示不需要(切断)与外围类实例对象关联
*/
private static class Node<T> {
/**
* 该节点的数据
*/
private T data;
/**
* 下一个节点,链表的最后一个节点的该值始终为null。可见性:默认包可见,方便获取操作
*/
Node<T> nextNode;
public Node(T data, Node<T> nextNode) {
this.data = data;
this.nextNode = nextNode;
}
public T getData() {
return data;
}
}
}
2、简单测试、使用
package testl.dataStructure.linkedList;
import org.junit.Test;
public class LinkedListTest {
@Test
public void testUse() {
LinkedList<String> link1 = new LinkedList<>();
link1.add("a");
link1.add("b");
link1.add("c");
link1.add("d");
System.out.println(link1.size());
//
System.out.println("------------------");
String[] list1 = link1.toArray(new String[] {});
for (String string : list1) {
System.out.println(string);
}
//
System.out.println("------------------");
System.out.println(link1.first());
System.out.println(link1.get(2));
System.out.println(link1.last());
}
}
结果如下:
4
------------------
a
b
c
d
------------------
a
c
d