天天看點

Java/206. Reverse Linked List 反轉連結清單題目

題目

Java/206. Reverse Linked List 反轉連結清單題目
Java/206. Reverse Linked List 反轉連結清單題目

代碼部分一(0ms 100% 疊代)

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

代碼部分二(0ms  100% 疊代)

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode tempNode = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tempNode;
        }
        return prev;
    }
}
           

代碼部分三(0ms 100% 遞歸)

class Solution {
    ListNode node, temp;
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode res = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }
}