LeetCode - 206. Reverse Linked List

Reverse a singly linked list.spa

Example:code

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:blog

A linked list can be reversed either iteratively or recursively. Could you implement both?get

反轉單鏈表,看到我好幾年前經過的代碼竟然是用List遍歷保存以後再倒序遍歷反轉,然而還RE了好幾回。。。往事忽然浮如今腦海,沒忍住又重寫了一下。it

耗時0msio

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, prev = null, temp = null;
        while (cur != null) {
            temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}

之前的代碼是這樣的(耗時464ms):class

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ArrayList<Integer> list = new ArrayList<Integer>();
        ListNode p = head;
        while(p!=null) {
            list.add(p.val);
            p = p.next;
        }
        ListNode q = head;
        for(int i=list.size()-1; i>=0; i--) {
            q.val = list.get(i);
            q = q.next;
        }
        return head;
        
    }
}
相關文章
相關標籤/搜索