【java数据结构】单链表实现

节点类:

package linkedList;
public class Node<T> {
    public T data;
    public Node<T> next = null;
    Node(T data) {  
        this.data = data;   
    }
}

单链表类:

package linkedList;

/**
 * 链表
 * 
 * @author Administrator
 * @param <T>
 *
 */
public class LinkedList<T> {
    private Node<T> head = null;
    public int length = 0;

    /**
     * 添加第节点
     * 
     * @param data
     */
    public Node<T> addNode(T data) {
        Node<T> node = new Node<T>(data);
        if (this.head == null) {

            this.head = node;
            head.next = head;
            length++;
            return node;
        } else {
            Node<T> curr = head;
            int pos = 0;
            while (pos != length - 1) {
                curr = curr.next;
                pos++;
            }
            curr.next = node;
            length++;
            return node;

        }
    }
    /**
     * 插入节点,在索引index之前
     * @param data
     * 节点数据
     * @param index
     * 索引
     * @return
     * 插入的节点
     */
    public Node<T> addNode(T data, int index) {
        Node<T> node = new Node<T>(data);
        Node<T> curr = head;
        int pos = 0;
        if (index == 0) {
            node.next = head;
            this.head = node;
            length++;
            return node;
        }
        if (index >= length) {
            System.out.println("插入点大于链表当前长度");
            return null;
        }
        while (pos != index - 1) {
            curr = curr.next;
            pos++;
        }
        node.next = curr.next;
        curr.next = node;
        length++;
        return node;
    }
        /**
     * 删除索引处的节点
     * @param index
     * 索引
     * @return
     * 被删除的节点
     */
    public Node<T> deleteNode(int index){
        if(index < 0 || index >=length) {
            System.out.println("索引超出范围,值:"+index);
            return null;
        }
        if(index == 0) {
            this.head = this.head.next;
            length--;
            return this.head;   
        }
        int pos = 0;
        Node<T> pioneer = head;
        while(pos != index - 1) {
            pioneer = pioneer.next;
            pos++;
        }
        Node<T> curr = pioneer.next;
        pioneer.next = curr.next;
        length--;
        return curr;

    }
    /**
     * 获取索引处的节点
     * 
     * @param index
     * @return
     */
    public Node<T> getNode(int index) {
        if(index < 0 || index >=length) {
            System.out.println("索引超出范围,值:"+index);
        }
        Node<T> curr = head;
        int pos = 0;
        while (pos != index) {
            curr = curr.next;
            pos++;
        }
        return curr;
    }
    /**
     * 获取所有节点
     * @return
     */
    public Node<?>[] getAllNode() {
        Node<?>[] node = new Node<?>[length];
        for (int i = 0; i < length; i++) {
            node[i] = getNode(i);
        }
        return node;
    }
}
posted @ 2017-08-09 00:02  SEC.VIP_网络安全服务  阅读(78)  评论(0编辑  收藏  举报