reverse a LinkedList

作者: Leahlijuan | 来源:发表于2019-07-24 10:59 被阅读0次

dummy -> 2 ->1 ->3
主要思想:把下一个元素插入dummy和已经reversed的序列之间。

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0), next = head;
        dummy.next = head;
        while(head.next != null) {
            next = dummy.next;
            dummy.next = head.next;
            head.next = head.next.next;
            dummy.next.next = next;
        }
        return dummy.next;
    }
}

相关文章

网友评论

    本文标题:reverse a LinkedList

    本文链接:https://www.haomeiwen.com/subject/kzwtrctx.html