【LeetCode-链表】面试题-反转链表

题目来源于 LeetCode 上第 206号(Reverse Linked List)问题:反转一个单链表。题目难度为 Easy。

题目地址:https://leetcode.com/problems/reverse-linked-list/

题目描述

Reverse a singly linked list.

反转一个单链表

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
复制代码
解法一: 递归
  1. 寻找递归结束条件:当链表只有一个节点,或者如果是空表的话,结束递归

    head == null || head.next  == null
    复制代码
  2. 调用函数本身,传入下一个节点

    reverseList(head.next);
    复制代码

    我们把 2->3->4->5 递归成了 5->4->3->2, 对于1节点没有去更改,所以1的next节点指向的是2,如下所示

    递归前:
    1 -> 2 -> 3 -> 4 -> 5
    
    递归后:
    1 -> 2 <- 3 <- 4 <- 5
         |
         v
        null
    复制代码
  3. 最后将节点 2 的 next 指向 1,然后把 1 的 next 指向 null,如下所示

    null <- 1 <- 2 <- 3 <- 4 <- 5
    复制代码

算法效率如下图所示:

代码实现
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next  == null) return head;
        
        ListNode nextNode = reverseList(head.next);
        
        ListNode tempNode = head.next;
        tempNode.next = head;
        head.next = null;
        
        return nextNode;
    }
}
复制代码
解法二: 原地逆置链表

设置三个节点 preNode, head, next

  1. 判断head 以及 head.next 是否为空,如果为空,结束循环
  2. 如果不为空,设置临时变量next为head的下一个节点
  3. head的下一个节点指向preNode,然后preNode移动到head, head移动到next
  4. 重复(1)(2)(3)

算法效率如下图所示:

代码实现
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode preNode = null;
        while (head!=null){
            ListNode next = head.next;
            head.next = preNode;
            preNode = head;
            head = next;
        }
        return preNode;
    }
}
复制代码

解法三:头插入法逆值链表

  1. 新建一个新链表, 新链表的头结点 newHead
  2. 循环判断head是否为空,为空时结束循环
  3. 如果不为空,依次取原链表中的每一个节点,作为第一个节点插入到新链表中

算法效率如下图所示:

代码实现
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newHead = new ListNode(0);
        while (head!=null){
            ListNode tempNode = new ListNode(head.val);
            tempNode.next = newHead.next;
            newHead.next = tempNode;
            head = head.next;
        }
        return newHead.next;
    }
}
复制代码
相关文章

【LeetCode-栈】有效的括号

【LeetCode-链表】面试题-反转链表

【LeetCode-二叉树】二叉树前序遍历

【LeetCode-数组】数组式整数加法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值