class="java" name="code">package test; public class LinkList { private static class Node{ int data; Node next; Node(int data){ this.data = data; this.next = null; } } Node head;//头结点 public LinkList(){//链表的构造方法 head = null; } public void clear(){//清空链表 head = null; } public void travel(){//遍历打印链表 Node p = head; while(p != null){ System.out.println(p.data); p = p.next; } } public boolean isEmpty(){//判断链表是否为空 return head == null; } public int size(){//得到节点的个数 Node p = head; int sum = 0; while(p != null){ sum++; p = p.next; } return sum; } public void insert(int value, int pos){//指定位置插入节点 if(pos < 0 || pos > size()){ throw new RuntimeException("下标异常"); } Node newNode = new Node(value); if(pos == 0){ newNode.next = head; head = newNode; }else if(pos >= (size()-1)){ get(size()-1).next = newNode; }else{ newNode.next = get(pos); get(pos-1).next = newNode; } } public Node get(int pos){//获取指定位置的节点 if(pos < 0 || pos >= size()){ throw new RuntimeException("下标出错"); } if(pos == 0){ return head; } Node p = head; for(int i=0;i<pos;i++){ p = p.next; } return p; } public void remove(int pos){//删除指定位置的元素 if(pos < 0 || pos >= size()){ throw new RuntimeException("下标出错"); } if(pos == 0){ head = head.next; }else if(pos >= (size()-1)){ Node temp = get(size()-1); temp = null; get(size()-2).next = null; }else{ get(pos-1).next = get(pos).next; Node posNode = get(pos); posNode = null; } } public static void main(String args[]){ LinkList ll = new LinkList(); ll.insert(1, 0); ll.insert(2, 1); ll.travel(); } }
?