编辑代码

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;
        }
    }
}