【发布时间】:2014-04-17 01:18:30
【问题描述】:
我需要知道如何反转我的链表。
我将发布我的 Node 和 LinkedList 类。另外两个是驱动程序(它创建了我的 TUI 类和我的 TUI 类的实例,它询问用户将哪个单词添加到 LinkedList,然后打印列表并反转它(通过调用 LinkedList 中的 reverse 方法,这就是我需要帮助)
我不知道在我的 LinkedList 中为 reverse 方法写什么
节点类:
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;
}
}
链表类:
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() {
}
}
【问题讨论】:
-
如果您扫描列表并向后更改所有链接会怎样?
-
我需要在LinkedList中有reverse方法。
-
哦,有人赞成这个..
-
迈克 B,我已经尝试将头部设置为尾部。我尝试了一个while循环(尽管我认为这是要走的路,但我知道我做错了)
标签: java linked-list reverse