单向链表-范例(java)

186 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

/**
 * 节点
 */
class Node{
    //数据域(可以是其它类型)
    public Integer data;
    //下一个节点
    public Node next;

    public Node(){

    }

    public Node(int data){
        this.data = data;
    }

    public Node(int data, Node next){
        this.data = data;
        this.next = next;
    }

    @Override
    public String toString() {
        return "node: data=" + data +"\n";
    }
}

/**
 * 单项链表
 */
public class LinkedList {
    //头节点
    private Node header = new Node(0);

    public LinkedList(){

    }

    public LinkedList(Node next){
        header.next = next;
    }

    /**
     * 添加节点
     * @param node
     */
    public void addNode(Node node){
        Node temp = header;
        while (true){
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }
        temp.next = node;
    }

    /**
     * 显示
     */
    public void show(){
        Node temp = header.next;
        while (true){
            if(temp == null){
                break;
            }
            System.out.printf(temp.toString());
            temp = temp.next;
        }
    }

    /**
     * 链表长度
     * @return
     */
    public int length(){
        int length = 0;
        Node temp = header.next;
        while (temp!=null){
            length++;
            temp = temp.next;
        }
        return length;
    }

    /**
     * 插入
     * @param node
     * @param index
     */
    public void insert(Node node, int index){
        if(index<1||index>length()){
            throw  new RuntimeException("插入位置不合法");
        }
        Node temp = header;
        int current = 0;
        while (temp.next !=null){
            if((index-1) == current){
                node.next = temp.next;
                temp.next = node;
                break;
            }
            current++;
            temp = temp.next;
        }

    }

    /**
     * 删除节点
     * @param index
     */
    public void deleteNode(int index){
        if(index<1||index>length()){
            throw  new RuntimeException("删除位置不合法");
        }
        Node temp = header;
        int current = 0;
        while (temp.next !=null){
            if((index-1) == current){
                temp.next = temp.next.next;
                break;
            }
            current++;
            temp = temp.next;
        }
    }

    /**
     * 查找节点
     * @param index
     * @return
     */
    public Node findNode(int index) {
        if (index < 1 || index > length()) {
            return null;
        }
        int current = 0;
        Node temp = header;
        Node node = null;
        while (temp.next != null) {
            if ((index - 1) == current) {
                node = temp.next;
                node.next = null;
                break;
            }
            current++;
            temp = temp.next;
        }
        return node;
    }
}