I know it is a minute code. I can't understand why my linked list reversal is not working. Can some one help fix me my reverse method in the below code.
//Reverse a single linked list
public Node reverse()
{
return reverse(root);
}
private Node reverse(Node node)
{
Node previous = null;
Node current = node;
Node forward;
while (current != null)
{
forward = current.next;
current.next = previous;
previous = current;
current = forward;
}
return previous;
}
Any input on this would be helpful
Thanks !!!
Assuming homework...
Write simple tests: list of 0 items, list of 1 items, list of 2 items, list of 10 items. Than make sure each of them work - will narrow down error and learn to write unit tests.
您确定使用返回值的reverse()而不是root进行迭代吗?
I'm pretty sure it should be
return root = reverse(root);
(Your reverse logic is correct, but if the root
is still pointing at the old root of the list, you will end up with a 1-element linked list.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.