zoukankan      html  css  js  c++  java
  • 循环单链表(七)

    循环单链表和单链表最大的区别是它的某个节点会指向该链表的头节点。通过循环你会发现该链表循环不尽,整个链表形成一个环。

    循环链表插入元素

     1、找到该链表的下一个节点

     2、新元素的下一个节点指向该链表的下一个节点。

     3、该链表的下个节点指向新元素。

    代码

    public class LoopNode {
    
        int data;
        //循环链表初始化 next默认为自身
        LoopNode next = this;
    
    
           public LoopNode after(LoopNode node) {
            LoopNode nextNodes = this.next;
            // 直接插入在当前节点后面 无法循环到最后一个
            node.next = nextNodes;
            // 最后一个节点下一个节点指向 node
            this.next = node;
            // 循环列表
            return this;
        }
    
    
    }

    删除节点

    1、找到该元素的下下个节点。

    2、当前链表的下个节点指向下下个节点。

    代码

    public class LoopNode {
    
        int data;
        //循环链表初始化 next默认为自身
        LoopNode next = this;
    // 删除节点
        public void remove() {
            // 先取出下下个节点
            LoopNode nextNode = next().next();
            this.next = nextNode;
        }
    
    }

    所有代码

    public class LoopNode {
    
        int data;
        //循环链表初始化 next默认为自身
        LoopNode next = this;
    
        public LoopNode(int data) {
            this.data = data;
        }
    
        public LoopNode after(LoopNode node) {
            LoopNode nextNodes = this.next;
            // 直接插入在当前节点后面 无法循环到最后一个
            node.next = nextNodes;
            // 最后一个节点下一个节点指向 node
            this.next = node;
            // 循环列表
            return this;
        }
    
        // 删除节点
        public void remove() {
            // 先取出下下个节点
            LoopNode nextNode = next().next();
            this.next = nextNode;
        }
    
        public LoopNode next() {
            return this.next;
        }
    
        public int getData() {
            return data;
        }
    
    }

    测试代码

    public class NodeTest {
    
        public static void main(String[] args) {
            LoopNode loopNode1 = new LoopNode(1);
            LoopNode loopNode2 = new LoopNode(2);
            LoopNode loopNode3 = new LoopNode(3);
            loopNode1.after(loopNode2);
            loopNode2.after(loopNode3);
            System.out.println(loopNode1.next.next.getData());
    
        }
    }
  • 相关阅读:
    数学图形之心形
    Nginx中文文档-安装 Nginx
    Mysql的row_format
    layui问题之模拟select点击事件
    深入理解HTTP协议、HTTP协议原理分析
    file_get_contents("php://input")的用法
    如何创建自己的composer包
    解决git pull/push每次都需要输入密码问题 和 HttpRequestException encountered
    微信网页授权 通过code获取openid 报错40163 code been used
    Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'userinfo.
  • 原文地址:https://www.cnblogs.com/laolei11/p/10643192.html
Copyright © 2011-2022 走看看