import java.util.Random;
public class Solution {
public static void main(String[ ] args) {
ListNode head = generateList();
System.out.print("原始链表:");
printList(head);
System.out.println();
ListNode newHead = reverseList(head);
System.out.print("反转链表:");
printList(newHead);
System.out.println( );
}
public static ListNode generateList( ) {
Random random = new Random();
ListNode head = new ListNode(random.nextInt(10));
ListNode tail = head;
for (int i = 1; i < 5; i++) {
ListNode node = new ListNode(random.nextInt(10));
tail.next = node;
tail = node;
}
return head;
}
public static ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
public static void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
}