数据结构指——单向链表

来源:互联网 发布:java 网络编程 编辑:程序博客网 时间:2024/05/17 04:34

什么是链表

链表是线性表的一种,所谓的线性表包含顺序线性表和链表,顺序线性表是用数组实现的,在内存中有顺序排列,通过改变数组大小实现。而链表不是用顺序实现的,用指针实现,在内存中不连续。意思就是说,链表就是将一系列不连续的内存联系起来,将那种碎片内存进行合理的利用,解决空间的问题。
所以,链表允许插入和删除表上任意位置上的节点,但是不允许随即存取。链表有很多种不同的类型:单向链表、双向链表及循环链表。
1、单向链表
单向链表包含两个域,一个是信息域,一个是指针域。也就是单向链表的节点被分成两部分,一部分是保存或显示关于节点的信息,第二部分存储下一个节点的地址,而最后一个节点则指向一个空值。

代码展示

public class SingleLink<Key, Value> {    public static void main(String[] args) {        SingleLink<String, String> singleLink = new SingleLink<String, String>();        singleLink.addNode("12", "23");        singleLink.addNode("22", "23");        singleLink.addNode("32", "23");        System.out.println(singleLink.get("12"));        System.out.println("开始移除12节点");        singleLink.deleteNode("22");        singleLink.print();    }    Node first;    /**     * 首节点操作     */    private class Node {        Key key;        Value value;        Node next;        public Node(Key key, Value value, Node next) {            this.key = key;            this.value = value;            this.next = next;        }    }    /**     * 添加节点操作     *     * @param key     * @param value     */    public void addNode(Key key, Value value) {        Node node = new Node(key, value, null);        /*首先判断首节点*/        if (this.first == null) {            this.first = node;        } else {            //类似于先进后出的操作            /**             * 新添加的默认就添加到header位置             */            first = new Node(key, value, this.first);        }    }    /**     * 输出内容     */    public void print() {        //尾节点是null        for (Node node = first; node != null; node = node.next) {            System.out.println(node.key + "--" + node.value);        }    }    public Value get(Key key) {        //查找给定的键,返回相关联的值信息        for (Node x = first; x != null; x = x.next) {            if (key.equals(x.key)) {                return x.value;            }        }        return null;    }    /*    *删除某个节点操作    * */    public void deleteNode(Key key) {        if (this.first == null) {            return;        }        if (this.first.key.equals(key)) {            this.first = this.first.next;        } else {            if (this.first.next != null) {                delete(this.first, key);            }        }    }    private void delete(Node previous, Key key) {        if (previous.next.key.equals(key)) {            previous.next = previous.next.next;        } else {            //递归删除操作            delete(previous.next, key);        }    }}
原创粉丝点击