206. Reverse Linked List 「反转链表」

反转一个单链表。

举例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

/*
 * 206. Reverse Linked List
 * https://leetcode.com/problems/reverse-linked-list/
 * https://www.whosneo.com/206-reverse-linked-list/
 */

public class ReverseList {
    public static void main(String[] args) {
        ReverseList solution = new ReverseList();

        ListNode head = new ListNode(1);
        ListNode node = head;
        for (int i = 2; i < 10; i++) {
            node.next = new ListNode(i);
            node = node.next;
        }

        solution.print(head);
        head = solution.reverseList(head);
        solution.print(head);
    }

    private void print(ListNode node) {
        for (; node != null; node = node.next) {
            System.out.print(node.val);
            System.out.print("->");
        }
        System.out.println("null");
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode node = head;

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

        return prev;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注