206. 反转链表

简单

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

迭代法

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode head2 = new ListNode();
        while (head != null) {
            ListNode t = head.next;
            head.next=head2.next;
            head2.next=head;
            head=t;
        }
        return head2.next;
    }
}

递归法★

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
分类: DS-Algo 标签: Java

评论

暂无评论数据

暂无评论数据

目录