问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

数据结构:循环链表

创作时间:
作者:
@小白创作中心

数据结构:循环链表

引用
CSDN
1.
https://m.blog.csdn.net/2302_80795993/article/details/144679198

数据结构是Java语言学习中的重要组成部分,其中循环链表是一个常见的数据结构。循环链表的特点是链表中的最后一个节点指向链表的头节点,形成一个闭环。与普通链表不同的是,循环链表中的快慢指针终将相遇,这一特性使得循环链表能够实现无限遍历循环的功能。

下面是一个循环链表的Java代码实现示例:

package Linear;
public class CircleListCheckTest {
    public static void main(String[] args) throws Exception {
        // 创建结点
        CircleListCheckTest.Node<String> first = new CircleListCheckTest.Node<>("aa", null);
        CircleListCheckTest.Node<String> second = new CircleListCheckTest.Node<>("bb", null);
        CircleListCheckTest.Node<String> third = new CircleListCheckTest.Node<>("cc", null);
        CircleListCheckTest.Node<String> fourth = new CircleListCheckTest.Node<>("dd", null);
        CircleListCheckTest.Node<String> fifth = new CircleListCheckTest.Node<>("ee", null);
        CircleListCheckTest.Node<String> six = new CircleListCheckTest.Node<>("ff", null);
        CircleListCheckTest.Node<String> seven = new CircleListCheckTest.Node<>("gg", null);
        // 完成结点之间的指向
        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;
        fifth.next = six;
        six.next = seven;
        // 产生环
        seven.next = third;
// 判断链表是否有环
        boolean circle = isCircle(first);
        System.out.println("first链表中是否有环: " + circle);
    }
    public static boolean isCircle(Node<String> first) {
        // 定义快慢指针
        Node<String> fast=first;
        Node<String> slow=first;
        // 遍历链表
        while(fast!=null && fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if (fast.equals(slow)){
                return true;
            }
        }
        return false;
    }
    private static class Node<T> {
        // 存储数据
        T item;
        // 下一个结点
        CircleListCheckTest.Node<T> next;
        public Node(T item, CircleListCheckTest.Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }
}

这段代码首先创建了多个节点,并通过指针将它们连接起来形成一个链表。然后,通过将最后一个节点的next指针指向链表中的某个中间节点,形成了一个环。最后,通过快慢指针的方法判断链表中是否存在环。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号