数据结构_链表实现无限循环的"环"结构/循环队列

本文介绍如何使用链表实现无限循环的环结构,并通过示例代码展示了向右、向左遍历以及删除元素的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       简单的数据结构应用,使用链表实现了"环"结构,代码如下:

package com.wly.algorithmbase.datastructure;

/**
 * 链表实现无限循环的"环",结构从左(head)到右(tail)
 * @author wly
 * @param <E>实体类
 */
class ChainCycle<E> {
	
	private Node<E> head; //头节点
	private Node<E> tail; //尾节点
	
	private Node<E> current; //当前遍历节点
	
	private int mSize = 0; //尺寸
	
	
	public static void main(String[] args) {
		ChainCycle<Student> chain = new ChainCycle<Student>();
		chain.insert(new Node<Student>(new Student("A",1)));
		chain.insert(new Node<Student>(new Student("B",2)));
		chain.insert(new Node<Student>(new Student("C",3)));

		System.out.println("向右遍历:");
		for(int i=0;i<6;i++) {
			Student s = chain.next();
			System.out.println(s.name + "_" + s.age);
		}
		System.out.println("向左遍历:");
		for(int i=0;i<6;i++) {
			Student s = chain.prev();
			System.out.println(s.name + "_" + s.age);
		}
		System.out.println("删除元素,并向右遍历:");
		chain.remove();
		for(int i=0;i<6;i++) {
			Student s = chain.prev();
			System.out.println(s.name + "_" + s.age);
		}

	}
	
	public E next() {
		if(current == null) {
			current = head;
		} else {
			current = current.right;
		}
		
		if(current != null) {
			return current.e;
		} else {
			return null;
		}
	}
	
	
	public E prev() {
		if(current == null) {
			current = head;
		} else {
			current = current.left;
		}
		
		if(current != null) {
			return current.e;
		} else {
			return null;
		}
	}
	
	/**
	 * 插入节点到尾节点
	 * @param node
	 */
	public void insert(Node<E> node) {
		if(tail == null) {
			head = node;
			tail = head;
			head.right = tail;
			head.left = tail;
			tail.right = head;
			tail.left = head;
		} else {
			head.left = node;
			tail.right = node;
			node.left = tail;
			node.right = head;
			tail = node;
			head.left = tail;
		}

		mSize ++;
	}
	
	/**
	 * 移除尾节点
	 */
	public void remove() {
		
		if(mSize == 0) {
			System.out.println("当前列表为空,无法再行移除元素!");
			return ;
		} else if(mSize == 1) {
			tail = null;
			head = null;
		} else {
			//连接新的tail和head
			head.left = tail.left;
			tail.left.right = head;
			tail = tail.left;
		}
	}
	
	public int size() {
		return mSize;
	}
}

/**
 * 节点类,封装了实体类E
 * @param <E> 
 */
class Node<E> {
	Node left;
	Node right;
	E e; //实体类
	public Node(E e) {
		this.e = e;
	}
}

/**
 * 测试实体类
 */
class Student {
	String name;
	int age;
	
	public Student(String name,int age) {
		this.age = age;
		this.name = name;
	}
}
       运行结果:
向右遍历:
A_1
B_2
C_3
A_1
B_2
C_3
向左遍历:
B_2
A_1
C_3
B_2
A_1
C_3
删除元素,并向右遍历:
B_2
A_1
B_2
A_1
B_2
A_1

       O啦~~~

       转载请保留出处:http://blog.youkuaiyun.com/u011638883/article/details/17302293

       谢谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值