数据结构与算法 | Leetcode 206:Reverse Linked List

前面我们实现了几种常见的 链表 ,接下来,我们来聊聊如何实现 单链表 的反转。

链表反转

Leetcode 206: Reverse Linked List

示例:

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

Input: NULL
Output: NULL
复制代码

我们可以通过循环遍历和递归这两种方式来实现链表的反转。

遍历

思路

定义三个指针,分别为prev、curr、next,然后遍历所有node结点,并移动这三个指针,改变curr结点的next指向,指向prev结点,实现linkedList的反转。

代码实现
/**
 * 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 prev = null;
        ListNode curr = head;
        ListNode next = null;
        while(curr != null){
            next = curr.next;
            curr.next = prev;        
            prev = curr;
            curr = next;
        }
        head = prev;
        return head; 
    }
}
复制代码

源码

递归

其实递归的实现方式和前面循环的方式非常相似,前者是通过循环来移动指针,后者是通过递归来移动指针。

定义一个递归接口,传入curr与prev节点作为参数,内部再将curr的作为下次递归调用的prev入参,curr.next 作为下次递归调用的curr入参。

代码实现
/**
 * 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 reverseRecursively(head, null);
    }
    
    public ListNode reverseRecursively(ListNode curr, ListNode prev) {
        if(curr == null){
            return null;
        }
        if(curr.next == null){
            ListNode head = curr;
            curr.next = prev;
            return head;
        }
        
        ListNode next1 = curr.next;
        curr.next = prev;
        
        ListNode head = reverseRecursively(next1, curr);
        return head;
    }
}
复制代码

源码

这两种方式的时间复杂度均为O(n),空间复杂度均为O(1)。

参考资料

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值