算法与数据结构笔记12——循环链表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengxu_kuangrexintu/article/details/87070816

循环链表概述

循环链表是另一种形式的链式存贮结构。表中最后一个结点的指针域指向头结点,整个链表形成一个环。

循环链表图

在这里插入图片描述

循环链表Demo

1.创建一个循环链表类LoopNode

package com.wyb.loop;

public class LoopNode {
	// 节点内容
	int data;
	
	// 下一个节点
	LoopNode next = this;
	
	public LoopNode(int data) {
		this.data = data;
	}
	
	// 删除下一个节点
	public void removeNext() {
		// 取出下下一个节点
		LoopNode newNext = next.next;
		// 把下下一个节点设置为当前节点的下一个节点
		this.next = newNext;
	}
	
	// 插入一个节点
	public void after(LoopNode node) {
		// 取出一个节点,作为下下一个节点
		LoopNode nextNext = next;
		// 把新节点作为当前节点的下一个节点
		this.next = node;
		// 把下下一个节点设置为新节点的下一个节点
		node.next = nextNext;	
	}
	
	// 获取下一个节点的方法
	public LoopNode next() {
		return this.next;
	}
	
	// 获取节点中的数据
	public int getDate() {
		return this.data;
	}
}

2.创建一个循环列表测试类TestLoopNode

package com.wyb.loop;

public class TestLoopNode {

	public static void main(String[] args) {
		LoopNode n1 = new LoopNode(1);
		LoopNode n2 = new LoopNode(2);
		LoopNode n3 = new LoopNode(3);
		LoopNode n4 = new LoopNode(4);
		// 增加节点
		n1.after(n2);
		n2.after(n3);
		n3.after(n4);
		System.out.println(n1.next().getDate());
		System.out.println(n2.next().getDate());
		System.out.println(n3.next().getDate());
		System.out.println(n4.next().getDate());
	}

}

循环链表的特点

循环链表的特点是无须增加存储量,仅对表的链接方式稍作改变,即可使得表处理更加方便灵活。

猜你喜欢

转载自blog.csdn.net/chengxu_kuangrexintu/article/details/87070816
今日推荐