算法系列——反转链表(Reverse Linked List)

301 阅读1分钟

题目描述

Given an array of integers, find out whether there are two distinct
indices i and j in the array such that the absolute difference between
nums[i] and nums[j] is at most t and the absolute difference between i
and j is at most k.

题目链接:leetcode-cn.com/problems/re…

解题思路

双指针法

题目要求反转链表,需要两个指针,pre,cur,pre指向当前要翻转的链表的前驱节点,cur指向当前要翻转的节点。时间复杂度为O(n)

递归法

递归的方法其实是非常巧的,它利用递归走到链表的末端,然后再更新每一个node的next 值 ,实现链表的反转。而newhead 的值没有发生改变,为该链表的最后一个结点,所以,反转后,我们可以得到新链表的head。时间复杂度为O(n)

程序实现

双指针法

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

递归法


public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}