很抱歉这个非常基本的问题我只允许使用Node<T>
课程,我正在尝试编写一个方法来反转列表,例如从2,4,6.8.10
到10,8,6,4,2
import java.util.Scanner;
public class Node<T> {
private T value;
private Node<T> next;
public Node(T value) {
this.value = value;
this.next = null;
}
public Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
public T getValue() {
return this.value;
}
public boolean hasNext() {
return this.next != null;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
public String toString()
{
return value + "--->" + next;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Node<Integer> n1 = new Node<Integer>(2);
Node<Integer> n2 = new Node<Integer>(4);
Node<Integer> n3 = new Node<Integer>(6);
Node<Integer> n4 = new Node<Integer>(8);
Node<Integer> n5 = new Node<Integer>(10);
n4.setNext(n5);
n3.setNext(n4);
n2.setNext(n3);
n1.setNext(n2);
reverse(n1);
}
private static void reverse(Node<Integer> l) {
//
Node<Integer> rev = new Node<Integer>(10);
while (l.hasNext()) {
rev.setNext(l.getNext());
System.out.println(rev.getValue());
}
System.out.println(l.toString());
}
}
答案 0 :(得分:1)
像
这样的东西private Node<T> reverse(Node<T> inputList) {
if (inputList == null || inputList.getNext() == null)
return inputList;
Node<T> secondPart = inputList.getNext();
inputList.setNext(null);
Node<T> reversed = reverse(secondPart);
secondPart.setNext(inputList);
return reversed;
}
它是如何运作的?
示例输入:[1, 5, 8, 9, 10]
take 1 and reverse [5, 8, 9, 10]
take 5 and reverse [8, 9, 10]
take 8 and reverse [9, 10]
take 9 and reverse [10]
return [10, 9] and append 8
return [10, 9, 8] and append 5
return [10, 9, 8, 5] and append 1
return [10, 9, 8, 5, 1]
答案 1 :(得分:1)
完整的通用提案:
class Node<T> {
...
@Override
public String toString() {
return value + (( next != null ) ? ( "--->" + next.toString()) : "" );
}
private Node<T> reverse( Function<Node<T>, Node<T>> factory, Node<T> n ) {
final Node<T> node = factory.apply( this );
node.setNext( n );
if( hasNext()) {
return getNext().reverse( factory, node );
}
return node;
}
public Node<T> reverse( Function<Node<T>, Node<T>> factory ) {
return reverse( factory, null );
}
}
public class ReverseList {
public static void main(String[] args) {
final Node<Integer> n1 = new Node<>( 2 );
final Node<Integer> n2 = new Node<>( 4 );
final Node<Integer> n3 = new Node<>( 6 );
final Node<Integer> n4 = new Node<>( 8 );
final Node<Integer> n5 = new Node<>( 10 );
n4.setNext(n5);
n3.setNext(n4);
n2.setNext(n3);
n1.setNext(n2);
System.err.println( n1 );
final Node<Integer> r = n1.reverse( n -> new Node<>( n.getValue()));
System.err.println( r );
}
}
执行:
2--->4--->6--->8--->10
10--->8--->6--->4--->2