LeetCode Question

reverse a LinkedList

2019-07-24  本文已影响0人  Leahlijuan

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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读