1创建节点类public class Node { public T data; public Node next; public Node(T data) { this.data = data; this.next = null; } }
2创建带泛型的链表类public class LinkedList { private Node head;//头节点; private Node tail;//尾节点; private int size;//记录整个链表的长度; public LinkedList() { this.head = null; this.tail = null; } //尾插法 public void addNode(T data){ if(head == null){ head = new Node(data); tail = head; size++; return; } tail.next = new Node(data); tail = tail.next; size++; } //打印链表;//其实可以用覆盖toString方法解决; public void print(){ Node 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 preNode = head; int count = 0; while(countsize) throw new RuntimeException('插入索引有错'); if(index==0){//在头结点之前插入 Node node = new Node(data); node.next = head; head = node; size++; return 0; } Node curNode = head; int count = 1; while(count node = new Node(data); node.next = curNode.next; curNode.next = node; size++; return index; }}
3编写测试用例public class LinkedListTest { @Test public void testPrint() { LinkedList 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 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+' '); } }}