循环链表是另一种形式的链式存储结构。它的特点是表中最后一个结点的指针域指向头结点,整个链表形成一个环。
代码实现:
public class MyCircleLinkedList { private Node head;//头结点, 不存数据 private Node tail;//尾结点, 指向链表的最后一个节点 private int size; public MyCircleLinkedList() { head = new Node(Integer.MIN_VALUE, null); head.next = head; tail = head; size = 0; } /** * 添加到链表尾部 * * @param item */ public void add(int item) { /********** Begin *********/ Node newNode = new Node(item,null); Node temp = head; for (int i = 0;i < size;i++){ temp = temp.next; } temp.next = newNode; newNode.next = head.next; tail = newNode; size++; /********** End *********/ } /** * 遍历链表并输出元素 */ public void output() { /********** Begin *********/ if (isEmpty()){ return; } Node temp = head.next; for (int i = 0;i < size;i++){ System.out.println(temp.item); temp = temp.next; } /********** End *********/ } /** * 删除从头结点开始的第index个结点 * index从0开始 * * @param index * @return */ public int remove(int index) { checkPosIndex(index); /********** Begin *********/ Node temp = head.next; for (int i = 0;i < size;i++){ if (i == index - 1){ break; } temp = temp.next; } Node reNode = temp.next; temp.next = temp.next.next; size--; return reNode.item; /********** End *********/ } public boolean isEmpty() { return head.next == head; } public int size() { return size; } //结点内部类 private static class Node { int item; Node next; Node(int item, Node next) { this.item = item; this.next = next; } } }
代码实现:
public class MyDoubleLinkedList { private Node head;//头结点 private Node tail;//指向链表的尾结点 private int size; public MyDoubleLinkedList() { head = new Node(null, Integer.MIN_VALUE, null); head.next = head.prev = head; tail = head; size = 0; } /** * 添加元素到表尾 * * @param item */ public void add(int item) { /********** Begin *********/ Node newNode = new Node(null, item, null); tail.next = newNode; newNode.prev = tail; newNode.next = head; head.prev = newNode; tail = newNode; ++size; /********** End *********/ } /** * 删除指定位置index出的结点,并返回其值 * * @param index * @return */ public int remove(int index) { checkPosIndex(index);// /********** Begin *********/ Node temp = head.next; for (int i = 0;i < size;i++){ if (i == index){ break; } temp = temp.next; } temp.prev.next = temp.next; temp.next.prev = temp.prev; return temp.item; /********** End *********/ } /** * 打印双向链表 * * @param flag true从左向右顺序打印, false从右向左顺序打印 */ public void printList(boolean flag) { Node f = head; if (flag) {//向右 while (f.next != head) { f = f.next; System.out.print(f.item + " "); } } else {//向左 while (f.prev != head) { f = f.prev; System.out.print(f.item + " "); } } } public int size() { return size; } //结点内部类 private static class Node { int item; Node next;//直接后继引用 Node prev;//直接前驱引用 Node(Node prev, int item, Node next) { this.prev = prev; this.item = item; this.next = next; } } }