加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java数据结构 - 单链表

发布时间:2020-12-15 07:34:24 所属栏目:Java 来源:网络整理
导读:class Node { // 节点内容 private int data; // 下一个节点 private Node next; public Node( int value) { this .data = value; } // 为节点追加节点 public Node append(Node node) { // 当前节点 Node currentNode = this ; // 循环向后找 while ( true
class Node {
    // 节点内容
    private int data;
    // 下一个节点
    private Node next;

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

    // 为节点追加节点
    public Node append(Node node) {
        // 当前节点
        Node currentNode = this;
        // 循环向后找
        while(true) {
            // 如果下一个节点为null,说明当前节点已经是最后一个节点
            if (currentNode.next == null) {
                break;
            }
            currentNode = currentNode.next;
        }
        // 把需要追加的节点追加为找到的当前节点的下一个节点
        currentNode.next = node;
        return this;
    }

    // 获取下一个节点
    public Node next() {
        return this.next;
    }

    // 获取节点中的数据
    public int getData() {
        return this.data;
    }

    // 当前节点是否是最后一个节点
    public boolean isLast() {
        return this.next == null;
    }

    // 删除下一个节点
    public void removeNext() {
        // 先取出下下一个节点
        Node nextNextNode = next.next;
        // 把下下一个节点设置为当前节点的下一个节点
        this.next = nextNextNode;
    }

    // 显示所有节点信息
    public void show() {
        Node currentNode = this;
        while (true) {
            System.out.print(currentNode.data+" ");
            // 取出下一个节点
            currentNode = currentNode.next;
            if (currentNode == null) {
                break;
            }
        }
        System.out.println();
    }

    // 插入一个节点作为当前节点的下一个节点
    public void insert(Node node) {
        // 取出下一个节点,作为下下一个节点
        Node nextNode = next;
        // 把新节点作为当前节点的下一个节点
        this.next = node;
        // 把下下一个节点设置为新节点的下一个节点
        node.next = nextNode;
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建节点
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);

        // 追加节点
        n1.append(n2).append(n3);

        // 取出下一个节点
        System.out.println(n1.next().next().getData());

        // 判断节点是否为最后一个节点
        System.out.println(n1.next().next().isLast());

        // 显示所有节点内容
        n1.show();

        // 删除一个节点
        n1.removeNext();
        n1.show();
        
        // 插入一个新节点
        n1.insert(new Node(2));
        n1.show();

        
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读