数据结构之----循环链表

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

分类
(1)单循环链表——在单链表中,将终端结点的指针域NULL改为指向表头结点或开始结点即可。
(2)多重链的循环链表——将表中结点链在多个环上。

空链判断

判断空链表的条件是
head==head->next;
rear==rear->next;
尾指针

用尾指针rear表示的单循环链表对开始结点a1和终端结点an查找时间都是O(1)。而表的操作常常是在表的首尾位置上进行,因此,实用中多采用尾指针表示单循环链表。带尾指针的单循环链表可见下图。
注意:判断空链表的条件为rear==rear->next;
特点

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

简单实现

public class CiNode {
	private Object data;
	private CiNode next;
	private static CiNode first; // 临时结点,头结点,并不是链表里想要的值,起到标记链表头的作用
	public CiNode() {
		super();
	}
	public CiNode(Object data, CiNode next) {
		super();
		this.data = data;
		this.next = next;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public CiNode getNext() {
		return next;
	}
	public void setNext(CiNode next) {
		this.next = next;
	}
	public static void add(CiNode node, int index) {
		if (index == 0) {
			node.next = first.next;
			first.next = node;
		} else {
			int temp = 0;
			for (CiNode n = first.next;; n = n.next) {
				temp++;
				if (temp == index) {
					node.next = n.next;
					n.next = node;
					break;
				}
			}
		}
	}
	public static void remove(int index) {
		if (index % 5 == 0) { // 删除第一个元素,考虑循环
			first.next = first.next.next;
		} else {
			int temp = 0;
			for (CiNode n = first.next;; n = n.next) {
				if (n == first) {
					temp -= 1; // 减一是因为链表循环计数时会把first记一次,所以这里减一次,使下标一致
				}
				temp++;
				if (temp == index) {
					n.next = n.next.next;
					break;
				}
			}
		}
	}
	public static void display() {
		for (CiNode n = first.next; n != first; n = n.next) {
			System.out.print(n.data + " ");
		}
		System.out.println();
	}
	public static void main(String[] args) {
		CiNode node4 = new CiNode("ddd", null);
		CiNode node3 = new CiNode("ccc", node4);
		CiNode node2 = new CiNode("bbb", node3);
		CiNode node1 = new CiNode("aaa", node2);
		first = new CiNode(null, node1);
		node4.next = first;
		System.out.println("当前链表:");
		display();
		add(new CiNode("eee", null), 5); // 传5进去是为了体现循环,当参数大于了链表长度时,又回到first
		System.out.println("插入后链表:");
		display();
		remove(11);
		System.out.println("删除后链表:");
		display();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BFP_BSP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值