[LeetCode] #206 反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

输入: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;
    }
}

知识点:

总结:

posted @ 2021-09-10 12:54  1243741754  阅读(22)  评论(0编辑  收藏  举报