所以基本上我创建了自己的linkedlist
类,现在我正在添加一个名为reverse
的函数来反转它。奇怪的是,它不起作用,我甚至无法调试!我不知道最新情况,如果有人可以提取我的代码并让我知道发生什么事情会让人感到惊讶。我在一个文件中有我的Node类和LinkedList
类,反向函数叫做reverse。如果你现在尝试使用反向,它不起作用,冻结调试器,甚至不让我在第一次迭代后逐步执行while循环。 (我正在使用IntelliJ
)
class Node<Type> {
private Type data;
private Node<Type> nextNode;
public Node(Type data) {
this.data = data;
}
public void setData(Type data) {
this.data = data;
}
public Type getData(){
return data;
}
public void setNextNode(Node<Type> nextNode) {
this.nextNode = nextNode;
}
public Node<Type> getNextNode() {
return nextNode;
}
@Override
public String toString(){
return "Data: " + this.data;
}
}
public class LinkedList<Type> {
private Node<Type> head;
private int length;
public LinkedList() {
length = 0;
}
// Returns: Pointer to the first Node in the list where Node.getData().equals(data)
// O(N)
public Node<Type> find(Type data) {
Node<Type> currentNode = head;
while(currentNode != null) {
if(currentNode.getData().equals(data)) {
return currentNode;
}
currentNode = currentNode.getNextNode();
}
return null;
}
// Returns: the length of the list
// O(1)
public int getLength() {
return length;
}
// Create a node with data and add it to the front of the list
// O(1)
public void addAtHead(Type data) {
Node<Type> newHead = new Node<Type>(data);
newHead.setNextNode(this.head);
this.head = newHead;
length += 1;
}
// Delete the head node (garbage collection)
// O(1)
public void deleteHead(){
if(this.head != null) {
this.head = this.head.getNextNode();
length -= 1;
}
}
public void reverse() {
Node<Type> rememberMe = head.getNextNode();
while(rememberMe != null) {
Node<Type> temp = head;
head = rememberMe;
rememberMe = head.getNextNode();
head.setNextNode(temp);
}
}
// Print out the node using node.toString
// Eg. { node1.toString() , node2.toString() , node3.toString() }
// O(N)
@Override
public String toString(){
String result = "{";
Node<Type> currentNode = this.head;
while(currentNode != null) {
result += " " + currentNode.toString() + " ";
currentNode = currentNode.getNextNode();
if(currentNode != null) {
result += ", ";
}
}
result += "}";
return result;
}
}
答案 0 :(得分:0)
反转之后,原始头部仍然有一个指向第二个元素的下一个元素,但现在是倒数第二个元素,所以在反转之后你会有一个循环结束。这意味着toString()函数中有一个无限循环,intellij调试器可能正在调用它。
要修复,请跟踪原始头部并将其下一个设置为空。
public void reverse() {
Node<Type> orig_head = head;
Node<Type> rememberMe = head.getNextNode();
while(rememberMe != null) {
Node<Type> temp = head;
head = rememberMe;
rememberMe = head.getNextNode();
head.setNextNode(temp);
}
orig_head.setNextNode(null);
}