Java语言定义双向链表,用的是LinkList类么?然后怎么实现双向队列呢?双向链表转换成双向队列的办法是什么
看下 是这个意思不 ?
代码:
import java.util.LinkedList;
import java.util.Queue;
public class HanoiTower {
public static void hanoiTower(int n, char start, char auxiliary, char end) {
Queue<String> queue = new LinkedList<>();
// 将初始移动任务加入队列
String task = n + " " + start + " " + auxiliary + " " + end;
queue.offer(task);
while (!queue.isEmpty()) {
// 取出队列中的任务
String currentTask = queue.poll();
String[] parts = currentTask.split(" ");
int disk = Integer.parseInt(parts[0]);
char from = parts[1].charAt(0);
char to = parts[3].charAt(0);
if (disk == 1) {
// 只有一个盘子时直接移动
System.out.println("将第1个盘子从柱子" + from + "移动到柱子" + to);
} else {
// 将当前任务拆分为三个子任务,分别放入队列中
char other = getOther(from, to);
String task1 = (disk - 1) + " " + from + " " + to + " " + other;
String task2 = "1 " + from + " " + other + " " + to;
String task3 = (disk - 1) + " " + other + " " + from + " " + to;
queue.offer(task1);
queue.offer(task2);
queue.offer(task3);
}
}
}
private static char getOther(char from, char to) {
if ((from == 'A' && to == 'B') || (from == 'B' && to == 'A')) {
return 'C';
} else if ((from == 'A' && to == 'C') || (from == 'C' && to == 'A')) {
return 'B';
} else {
return 'A';
}
}
public static void main(String[] args) {
int n = 3;
hanoiTower(n, 'A', 'B', 'C');
}
}
参考这个文章:https://blog.csdn.net/weixin_44918667/article/details/124411033
/*
* 定义单链表
*/
public class LinkList<T> {
private Node<T> head;
private int length;
//初始化一个空链表
public LinkList(){
length = 0;
head = new Node<T>(null);
}
//取得头节点
public Node<T> getHead(){
return head;
}
//在链表指定位置插入一个新元素
public boolean add(T obj,int pos){
if(pos<1 || pos>length+1){
System.out.println("pos值不合法");
return false;
}
int num = 1;
Node<T> p = head;
Node<T> q = head.next;
/*当num的值等于pos时循环停止,找到要插入的位置,
p为pos位置的前一个元素,q为pos位置的元素*/
while(num<pos){
p = q;
q = q.next;
num++;
}
p.next = new Node<T>(obj,q);//完成插入
length++;
return true;
}
//判断单链表是否为空
public boolean isEmpty(){
return length == 0;
}
//返回单链表的长度
public int size(){
return length;
}
//正序输出单链表中所有元素
public void nextOrder(){
Node<T> p = head.next;
while(p != null){
System.out.print(p.data+" ");
p = p.next;
}
System.out.println();
}
/**
* 单链表转置方法
* @MethodName: getInversionList
* @Description: void
* @throws
*/
public void getInversionList(){
if(isEmpty()){
//判断是否为空
System.out.println("顺序表为空");
}else{
Node<T> temp1,temp2;
temp1=head.next;
head.next=null;
while (temp1!=null) {
temp2=temp1.next;
temp1.next=head.next;
head.next=temp1;
temp1=temp2;
}
}
}
public static void main(String[] args) {
LinkList<Integer> linkList = new LinkList<Integer>();
linkList.add(-5, 1);
linkList.add(-1, 2);
linkList.add(8, 3);
linkList.add(1, 4);
linkList.add(2, 5);
System.out.print("转置前:");
linkList.nextOrder();
System.out.print("转置后:");
linkList.getInversionList();
linkList.nextOrder();
}
}