天天看点

LeetCode 206. Reverse Linked List(链表)206. Reverse Linked List

题目来源:https://leetcode.com/problems/reverse-linked-list/

问题描述

206. Reverse Linked List

Easy

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

------------------------------------------------------------

题意

单链表反转。

------------------------------------------------------------

思路

【循环解法】

维护三个指针head, tmp, ptr,head指向当前节点,tmp指向原链表里当前节点的后继节点,ptr指向原链表里当前节点的前驱节点。顺序遍历原链表,每次将head.next指向ptr,但是原链表的头指针要指向null. 

时间复杂度O(n),空间复杂度O(1).

【递归解法】

在节点head处,递归方法recuReverse首先递归调用自身(参数为下一个节点head.next)将head之后的链表反转,再用head.next指向head, head指向null(为了处理原链表的首节点)。

时间复杂度O(n),空间复杂度O(n). (递归的空间复杂度为递归栈的深度)

------------------------------------------------------------

代码

【循环解法】

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null)
        {
            return null;
        }
        ListNode ptr = null, tmp = null;
        while (true)
        {
            tmp = head.next;
            if (ptr == null)
            {
                ptr = head;
                ptr.next = null;
            }
            else
            {
                head.next = ptr;
                ptr = head;
            }
            if (tmp == null)
            {
                return head;
            }
            head = tmp;
        }
    }
}
           

【递归解法】

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null)
        {
            return null;
        }
        return recuReverse(head);
    }
    
    private ListNode recuReverse(ListNode head) {
        if (head.next == null)
        {
            return head;
        }
        ListNode newHead = recuReverse(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}