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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38959715/article/details/83277467