我需要知道如何撤销我的链接列表。
我将发布我的Node和LinkedList类。另外两个是驱动程序(它创建了我的TUI类的实例和我的TUI类,它询问用户将哪个单词添加到LinkedList然后打印列表并将其反转(通过调用LinkedList中的反向方法,这就是我需要帮助)
我不知道在我的LinkedList
中为反向方法写什么节点类:
public class Node {
private String data;
private Node next;
public Node(String data, Node next) {
this.data = data;
this.next = next;
}
public Node(String data) {
this.data = data;
this.next = null;
}
public String getData() {
return this.data;
}
public Node getNext() {
return this.next;
}
public void setNext(Node nextNode) {
this.next = nextNode;
}
public String toString() {
return this.data;
}
}
Linked List类:
public class LinkedList {
private Node head;
private Node tail;
public LinkedList() {
this.head = null;
this.tail = null;
}
public void prepend(String data) {
Node newNode = new Node(data, this.head);
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
public void printList() {
Node current = this.head;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
public void append(String data) {
Node newNode = new Node(data);
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.setNext(newNode);
this.tail = newNode;
}
}
public void reverse() {
}
}
答案 0 :(得分:2)
这应该可以胜任。我们的想法是,对于每个列表节点,临时复制其下一个节点,将其旁边的节点设置为下一个节点,然后将上一个节点设置为它。它也可以递归完成。
public void reverse() {
Node prev = null;
Node current = head;
while (current != null) {
Node next = current.getNext();
current.setNext(prev);
prev = current;
current = next;
}
this.head = prev;
}
编辑:您还需要更新尾部参考