双向循环链表:移位输出26位字母
实现用户输入一个数使得26个字母的排列发生变化,例如用户输入3,输出结果:
-D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
同时支持用户负数输出,例如输入-3,输出结果:
-X Y Z A B C D E F G H I J K L M N O P Q R S T U V W
算法:
/**
* @Author RunXin
* @Date 2021/7/14 9:28
* @description
*/
public class PerPrint {
public static void PerPrintMethod(int num){
CircularNode head = new CircularNode();
CircularNode cur = head;
int enNum = 26;
char init = 'A';
// 构建26个字母的双向循环链表
for (int i = 0; i < enNum; i++) {
CircularNode circularNode = new CircularNode((char) (init + i));
cur.next = circularNode;
circularNode.pre = cur;
cur = circularNode;
}
// 首尾相连
cur.next = head.next;
head.next.pre = cur;
for (int i = 0; i < Math.abs(num); i++) {
if(num >= 0){
head.next = head.next.next;
}else {
head.next = head.next.pre;
}
}
// 验证是不是已经构成一个双向循环链表
for (int i = 0; i < enNum; i++) {
head = head.next;
System.out.println(head.data);
}
// while (head.pre != null){
// head = head.pre;
// System.out.println(head.data);
// }
}
public static void main(String[] args) {
PerPrintMethod(-3);
}
}
/**
* 双向循环链表
*/
class CircularNode{
CircularNode pre;
CircularNode next;
char data;
public CircularNode() {
}
public CircularNode(char data) {
this.data = data;
}
}