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

来源:互联网 发布:苹果刷机后数据恢复 编辑:程序博客网 时间:2024/06/06 20:47

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

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和headhead.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_1B_2C_3A_1B_2C_3向左遍历:B_2A_1C_3B_2A_1C_3删除元素,并向右遍历:B_2A_1B_2A_1B_2A_1

       O啦~~~

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

       谢谢!!

0 0
原创粉丝点击