[英]Reversing a Linked List not working as expected
I am currently trying to reverse a linked list, I have an unexpected problem where it doesn't print correctly.我目前正在尝试反转链接列表,但遇到了无法正确打印的意外问题。 And when I try and access the values of the linked list I get an error.
当我尝试访问链表的值时,我得到一个错误。 I would greatly appreciate an expert eye to see what I am missing.
我将不胜感激专家的眼睛,看看我错过了什么。 Thanks in advance.
提前致谢。
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
private E data; // reference to the element stored at this node
private Node<E> nextNode;
//methods for accessing variables
public Node<E> getNextNode() { return nextNode; }
public E getData() { return data; }
// Modifier methods
public void setNext(Node<E> n) { nextNode = n; }
public void setData(E n) { data = n; }
public Node(E e, Node<E> n) {
nextNode = n;
data = e;
}
// reference to the subsequent node in the list// TODO
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private int size = 0; // number of nodes in the list
private Node<E> head = null; // head node of the list (or null if empty)
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* @return number of elements in the linked list
*/
public void addFirst(E e) {
head = new Node<E>(e, head); // create the new node and link new node
size++;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder temporaryString = new StringBuilder();
temporaryString.append("[");
for(Iterator<E> iterator = iterator(); iterator.hasNext();){
temporaryString.append(iterator.next()).append(", ");
}
temporaryString.deleteCharAt(temporaryString.length() - 1);
temporaryString.deleteCharAt(temporaryString.length() - 1);
temporaryString.append("]");
return temporaryString.toString();
}
private class SinglyLinkedListIterator implements Iterator<E> {
private Node<E> current;
public SinglyLinkedListIterator() {
current = head;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public E next() {
if(!hasNext()) throw new RuntimeException("No such element");
E res = current.getData();
current = current.getNextNode();
return res;
}
}
public Iterator<E> iterator() {
return new SinglyLinkedListIterator();
}
The reverse Linked List method:反向链表方法:
public Node<E> reverseLinkedList(SinglyLinkedList sll) {
Node<E> previous = null;
Node<E> current = sll.head;
while (current != null) {
Node<E> nextElement = current.getNextNode();
current.setNext(previous);
previous = current;
current = nextElement;
}
return previous;
}
The main method:主要方法:
public static void main(String[] args) {
SinglyLinkedList<Integer> sll2 = new SinglyLinkedList<Integer>();
sll2.addFirst(1);
sll2.addFirst(2);
sll2.addFirst(3);
System.out.println(sll2.toString());
sll2.reverseLinkedList(sll2);
System.out.println(sll2.toString());
}
The output: output:
[3, 2, 1]
//i should expect to get 1,2,3
[3]
As you are mutating ("rewiring") the given linked list in the reverseLinkedList
function, you are not actually producing a new linked list.当您在
reverseLinkedList
function 中对给定的链表进行变异(“重新布线”)时,您实际上并没有生成新的链表。 So to have it return something is actually contradictory.所以让它返回一些东西实际上是矛盾的。 Either it should return a completely new linked list without mutating the given one, or it should mutate the given linked list and not return anything.
要么它应该返回一个全新的链表而不改变给定的链表,要么它应该改变给定的链表而不返回任何东西。
From your main
code I see that you actually expect to mutate the given linked list, as you don't use the returned value and print the result based on sll
.从您的
main
代码中,我看到您实际上希望改变给定的链表,因为您不使用返回的值并基于sll
打印结果。 So make your function a void
one, and drop the return
statement.因此,使您的 function 成为
void
的,并删除return
语句。
The core problem now is that you never change the head
member: it still references what used to be the first node in the list, but is now the last one.现在的核心问题是您永远不会更改
head
成员:它仍然引用过去是列表中的第一个节点,但现在是最后一个。 You should assign the node to head
that previously was the tail node.您应该将该节点分配给以前是尾节点的
head
。
So the last statement in your function should be:所以 function 中的最后一条语句应该是:
sll.head = previous;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.