public class linklist{ private class Node{ private T info; private Node next; public Node(T info,Node next){ this.info = info; this.next = next; } } private Node head;//头节点 private int size;//链表长度 //构造方法 public linklist(Node head,int size){ this.head = head; this.size = size; } public linklist() { } public int getSize(){ return this.size; } //向链表头节点前面添加一个节点,其数据域为info public void addHead(T info){ this.head = new Node(info,head); this.size++; } //尾插法 public void addLast(T info){ this.add(info,this.size); } //插入指定位置 public void add(T info,int index){ if(index < 0 || index > size) return; else if(index == 0){ addHead(info); return; } Node pre = this.head;//找到添加位置的前一个节点 for(int i = 0;i < index-1;i++){ pre = pre.next; } Node node = new Node(info,pre.next); pre.next = node; this.size++; } //删除任意位置的结点 public void delete(Node head,int index){ if(head == null) return; if(index < 0 || index > size-1) return; if(index == 0){ this.head = head.next; } Node front = this.head;//指向删除节点前面的节点 Node rear = this.head;//指向删除节点 for(int i = 0;i "); } else{ System.out.print(h.info); } h = h.next; } System.out.println('n'); } public static void main(String[] args) { linklist s = new linklist<>(); for (int i = 0; i < 5; i++) { s.addHead(i); } s.add(7,4); System.out.println(s.search(3)); s.travel(s.head); s.delete(s.head,4); s.travel(s.head); s.invert(s.head); s.travel(s.head); } }
输出结果:
1
4->3->2->1->7->0
4->3->2->1->0
0->1->2->3->4



