java 有序链表

/**
 * 有序链表
 */
public class LinkSort {
    class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
            this.next = null;
        }
    }

    private int size;
    private Node head;

    private LinkSort() {
        this.size = 0;
        this.head = null;
    }

    /**
     * 插入
     *
     * @param data 数值
     */
    private void insert(int data) {

        Node node = new Node(data);

        Node pre = null;
        Node cur = this.head;
        while (cur != null && cur.value < data) {
            pre = cur;
            cur = cur.next;
        }
        node.next = cur;
        if (pre == null) {
            this.head = node;
        } else {
            pre.next = node;
        }

        size++;
    }

    /**
     * 删除
     *
     * @param data 数值
     */
    private void delete(int data) {
        Node pre = null;
        Node cur = this.head;
        while (cur != null) {
            if (cur.value == data) {
                while (cur.next != null && cur.next.value == data) {
                    cur = cur.next;
                }
                if (pre != null) {
                    pre.next = cur.next;
                } else {
                    //第一个
                    this.head = cur.next;
                }
                return;
            }
            pre = cur;
            cur = cur.next;
        }
    }


    @Override
    public String toString() {
        Node node = this.head;
        StringBuilder stringBuilder = new StringBuilder();
        while (node != null) {
            stringBuilder.append("->").append(node.value);
            node = node.next;
        }

        return "LinkSort{" +
            "size=" + size +
            ", head=" + head +
            ", toString=" + stringBuilder.toString() +
            '}';
    }

    public static void main(String[] args) {
        LinkSort linkSort = new LinkSort();
        System.out.println(linkSort);
        linkSort.insert(3);
        System.out.println(linkSort);
        linkSort.insert(1);
        System.out.println(linkSort);
        linkSort.insert(2);
        System.out.println(linkSort);
        linkSort.insert(4);
        System.out.println(linkSort);
        linkSort.insert(4);
        System.out.println(linkSort);
        linkSort.insert(5);
        System.out.println(linkSort);
        linkSort.delete(4);
        System.out.println(linkSort);
        linkSort.delete(1);
        System.out.println(linkSort);
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容