剑指 Offer 24. 反转链表

目录

    • 迭代(双指针)
    • 递归

题目来源
剑指 Offer 24. 反转链表

迭代(双指针)

时间复杂度 O(N) : 遍历链表使用线性大小时间。
空间复杂度 O(1) : 变量 pre 和 cur 使用常数大小额外空间。

剑指 Offer 24. 反转链表_第1张图片

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
        
    }
}

剑指 Offer 24. 反转链表_第2张图片

递归

考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。
recur(cur, pre) 递归函数:

  • 1.终止条件:当 cur 为空,则返回尾节点 pre (即反转链表的头节点);
  • 2.递归后继节点,记录返回值(即反转链表的头节点)为 res ;
  • 3.修改当前节点 cur 引用指向前驱节点 pre ;
  • 4.返回反转链表的头节点 res ;

reverseList(head) 函数:
调用并返回 recur(head, null) 。传入 null 是因为反转链表后, head 节点指向 null ;

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

    public ListNode recur(ListNode cur,ListNode pre){
        if(cur == null){
            return pre;
        }
        ListNode res = recur(cur.next, cur);
        cur.next = pre;
        return res;
    }
}

剑指 Offer 24. 反转链表_第3张图片

你可能感兴趣的:(西南科技大学算法,链表,数据结构,leetcode)