天天看點

[LeetCode] #206 反轉連結清單

[LeetCode] #206 反轉連結清單

給你單連結清單的頭節點

head

,請你反轉連結清單,并傳回反轉後的連結清單。
[LeetCode] #206 反轉連結清單

輸入:head = [1,2,3,4,5]

輸出:[5,4,3,2,1]

疊代,需要一個臨時變量先儲存下一個節點

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode p1 = null,p2 = head;
        while(p2 != null){
            ListNode temp = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = temp;
        }
        return p1;
    }
}      
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newListNode = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newListNode;
    }
}