反转链表 java


public class Reword {

public static void main(String[] args){
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
print(node1);
print(swap(node1));
}

public static Node swap (Node n1){
Node result;
Node next = n1.next;
Node n = n1;
n.setNext(null);
if (next == null) {
result = n;
} else {
result = swap(next);
next.setNext(n);
}
return result;
}

public static void print(Node n){
do{
System.out.print(n.toString());
n = n.next;
}while (n.next != null);
System.out.print(n.toString());
System.out.println();
}

}

class Node {
public int data;
public Node next;
public Node(int data){
this.data = data;
}

public void setNext(Node node){
next = node;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return " "+data;
}
}

猜你喜欢

转载自zjingye.iteye.com/blog/2039518