package com.wyl.linklist; /** * 双向链表,实现26个字母的循环输出 * @author wyl * */ public class MyBinaryLink { private Node head; //定义双线链表的头结点 /** * 定义双向链表的节点类 */ class Node{ private char data; //节点的值 private Node prior; //前驱节点 private Node next; //后继节点 public Node() { } public Node(char data) { this(data, null, null); } public Node(char data, Node prior, Node next) { this.data = data; this.prior = prior; this.next = next; } public char getData() { return data; } public void setData(char data) { this.data = data; } public Node getPrior() { return prior; } public void setPrior(Node prior) { this.prior = prior; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } } /** * 构造函数初始化双向链表 */ public MyBinaryLink(){ head = new Node('A', null, null); Node p = head; int i=1; for(;i<26;i++){ if(p.next == null){ char data = (char) ('A' + i); Node newNode = new Node(data, p, null); p.next = newNode; p = p.next; } } p.next = head; head.prior = p; } /** * 打印双向链表的值 */ public void print(){ Node p = head; while(p.next != head){ System.out.print(p.data + "、"); p = p.next; } System.out.print(p.data); } /** * 从链表的某个位置开始打印 * @param num 表示从链表的第几个位置开始打印 */ public void printFrom(int num){ int i = 1; Node p = head; Node rear = head.prior; //找到链表的尾节点 Node start ; if(num > 0){ for(;i<num;i++){ p = p.next; } start = p; while(p.next != start){ System.out.print(p.data); p = p.next; } System.out.print(p.data); }else{ for(;i<-num;i++){ rear = rear.prior; } start = rear; while(rear.next != start){ System.out.print(rear.data); rear = rear.next; } System.out.print(rear.data); } } public static void main(String[] args) { MyBinaryLink myBinaryLink = new MyBinaryLink(); myBinaryLink.print(); System.out.println(); myBinaryLink.printFrom(4); System.out.println(); myBinaryLink.printFrom(-2); } }