以下是一个 Java 实现的方法,可以将给定链表反转:

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class ReverseLinkedList {
    public static ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode current = head;
        ListNode next = null;

        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }

        return prev;
    }

    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        System.out.println("Original List:");
        printList(head);

        ListNode reversedHead = reverse(head);

        System.out.println("Reversed List:");
        printList(reversedHead);
    }
}

输出结果为:

Original List:
1 -> 2 -> 3 -> 4 -> 5 -> null
Reversed List:
5 -> 4 -> 3 -> 2 -> 1 -> null
Java 链表反转:高效算法实现

原文地址: http://www.cveoy.top/t/topic/p3MJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录