温馨提示×

java链表反转代码怎么写

小亿
107
2023-12-11 14:01:44
栏目: 编程语言

以下是Java中链表反转的示例代码:

public class ListNode {
    int val;
    ListNode next;

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

public class LinkedListReverse {
    public static ListNode reverseList(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 main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ListNode reversedHead = reverseList(head);

        System.out.print("Reversed List: ");
        while (reversedHead != null) {
            System.out.print(reversedHead.val + " ");
            reversedHead = reversedHead.next;
        }
    }
}

运行以上代码,将会输出反转后的链表:

Reversed List: 5 4 3 2 1

在反转链表的代码中,我们使用了三个指针prev、current和next。初始时,prev为null,current为头节点head,next为null。在每一次循环中,我们将current的next指针指向prev,然后依次向后移动prev、current和next指针。最终,prev指针将指向反转后的链表头节点,我们将其返回即可。

0