反转一个单向链表。
public class ReversingLinkedList {
static class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
public boolean hasNext() {
return next != null;
}
}
public static void main(String[] args) {
//构造
Node head = null;
Node shift = null;
for (int i = 1; i <= 10; i++) {
Node node = new Node(i);
if (head == null) {
head = node;
shift = node;
} else {
shift.next = node;
shift = node;
}
}
print(head);
//反转
Node tail = null;
while (head.hasNext()) {
//a
Node tmp = head;
//b
head = head.next;
//c
tmp.next = tail;
//d
tail = tmp;
}
head.next = tail;
tail = head;
print(tail);
}
static void print(Node node) {
while (node.hasNext()) {
System.out.print(node.val + " -> ");
node = node.next;
}
System.out.println(node.val);
}
}