链表 java实现
1、创建节点类
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
}
2、创建带泛型的链表类
public class LinkedList<T> {
private Node<T> head;//头节点;
private Node<T> tail;//尾节点;
private int size;//记录整个链表的长度;
public LinkedList() {
this.head = null;
this.tail = null;
}
//尾插法
public void addNode(T data){
if(head == null){
head = new Node<T>(data);
tail = head;
size++;
return;
}
tail.next = new Node<T>(data);
tail = tail.next;
size++;
}
//打印链表;//其实可以用覆盖toString方法解决;
public void print(){
Node<T> curNode = head;
while(curNode!=null){
System.out.print(curNode.data+" ");
curNode = curNode.next;
}
System.out.println();
}
/**
* 删除第index个节点
* 返回 true,false
*/
public boolean deleteNode(int index){
if(index<0||index>size){
throw new RuntimeException("删除节点异常");
}
if(index==0){
head = head.next;
size--;
return true;
}
Node<T> preNode = head;
int count = 0;
while(count<index-1){
preNode = preNode.next;
count++;
}
preNode.next = preNode.next.next;
size--;
return true;
}
/**
* 插入指定索引出的值
* true or false
*/
public int insert(int index,T data){
if(index<0||index>size)
throw new RuntimeException("插入索引有错");
if(index==0){//在头结点之前插入
Node<T> node = new Node<T>(data);
node.next = head;
head = node;
size++;
return 0;
}
Node<T> curNode = head;
int count = 1;
while(count<index){
curNode = curNode.next;
count++;
}
Node<T> node = new Node<T>(data);
node.next = curNode.next;
curNode.next = node;
size++;
return index;
}
}
3、编写测试用例
public class LinkedListTest {
@Test
public void testPrint() {
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.addNode(1);
linkedList.addNode(2);
linkedList.addNode(3);
linkedList.addNode(4);
linkedList.addNode(5);
linkedList.print();
linkedList.deleteNode(4);//删除3;
linkedList.print();
}
@Test
public void testInsert() {
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.addNode(1);
linkedList.addNode(2);
linkedList.addNode(3);
linkedList.addNode(4);
linkedList.addNode(5);
linkedList.print();
linkedList.insert(4, 10);
linkedList.print();
}
@Test
public void test2() {
for( int i = -128;i<128;i++){
System.out.println((char)i+" ");
}
}
}