public class MyLinkedList {

    public ListNode head;

    /**
     * 链表头插入
     * @param data
     */
    public void insertHead(Object data){
        ListNode newData = new ListNode(data);
        // 如果存在链表头
        newData.next = head;
        head = newData;
    }

    /**
     * @param data
     * @param pos
     */
    public void insertNth(Object data, Integer pos){
        // 如果位置是链表头,直接交给insertHead 执行
        ListNode newData = new ListNode(data);
        if(pos == 0){
            insertHead(data);
        }else{
            ListNode cur = head;
            // 找到pos前的节点
            for(int i= 1; i < pos; i++){
                cur = cur.next;
            }
            newData.next = cur.next;
            cur.next = newData;
        }
    }

    /**
     * 尾部插入
     * @param data
     */
    public void insertNth(Object data){
        ListNode newData = new ListNode(data);
        ListNode cur = head;
        // 找到pos前的节点
        while (cur.next != null){
            cur = cur.next;
        }
        cur.next = newData;
    }

    /**
     * 删除表头
     */
    public void deleteHead(){
        head = head.next;
    }

    /**
     * 删除随机位置的节点
     * @param pos
     */
    public void deleteNode(Integer pos){
        if(pos == 0){
            deleteHead();
        }else{
            ListNode cur = head;
            // 找到pos前节点
            for (int i = 1; i < pos; i++){
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
    }

    /**
     * 更新某个节点的数据
     * @param pos
     */
    public void updateNode(Object data, Integer pos){
        if(pos == 0){
            head = new ListNode(data);
        }else{
            ListNode cur = head;
            // 找到pos节点
            for (int i = 0; i < pos; i++){
                cur = cur.next;
            }
            cur.data = data;
        }
    }

    /**
     * 打印节点数据
     */
    public void printNode(Integer pos){
        if(pos == 0){
            System.out.println(head);
        }else{
            ListNode cur = head;
            // 找到pos节点
            for ( int i = 0; i<pos; i++){
                cur = cur.next;
            }
            System.out.println(cur.data);
        }
    }

    /**
     * 打印整个链表
     */
    public void printList(){
        ListNode cur = head;
        System.out.println(cur.data);
        while (cur.next != null){
            System.out.println(cur.next.data);
            cur = cur.next;
        }
    }

    /**
     * 节点对象
     */
    public class ListNode{
        public Object data;
        public ListNode next = null;

        ListNode(Object data){
            this.data = data;
        }
    }
}

Devilu
85 声望4 粉丝

just a newbie