java单链表反转的方法是什么

lewis 2016-10-29 18次阅读

要实现单链表的反转,可以通过以下方法:

public class ReverseLinkedList {

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode current = head;
        
        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        
        return prev;
    }
}

在这个方法中,我们使用三个指针来遍历链表并反转节点的指向。prev指向当前节点的前一个节点,current指向当前节点,next指向当前节点的下一个节点。我们遍历链表,将当前节点的指向改为prev,然后分别移动prev、current、next指针,直到遍历完整个链表。最后返回prev即为反转后的链表头节点。



发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。