​LeetCode刷题实战206:反转链表

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 反转链表,我们先来看题面:

https://leetcode-cn.com/problems/reverse-linked-list/

Given the head of a singly linked list, reverse the list, and return the reversed list.

题意

反转一个单链表。

示例

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

解题

思路一:递归地反转链表

递归的终止条件:

(1)head为null,直接返回head。

(2)head.next为null,直接返回head。

递归的过程:

我们新的头节点记为newHead,其值应该是翻转以head.next为头节点的链表的结果。同时把head放在head.next的后面,并令head.next为null,这样我们就把head元素放在了新链表的末尾。

由于涉及到递归,而每一次递归的时间复杂度都是O(1)级别的,因此时间复杂度和空间复杂度都是O(n)级别的,其中n为链表中的节点个数。

JAVA代码:

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

思路二:非递归地反转链表

链表相关的题,多设指针,在草稿纸上多演练几次,一定能够轻松解决。

设立虚拟头节点dummyHead和三个指针cur1、cur2、cur3反转链表。

令cur1指向虚拟头节点dummyHead。

如果cur1.next是一个空节点或者说cur1.next.next是一个空节点,即链表中没有节点或链表中只有一个节点,无需翻转,直接返回head即可。

令cur2指向cur1.next,cur3指向cur2.next。在我的定义中,cur2指向的是待处理节点的前一个节点,cur3指向的是待处理节点。只要cur3不为null,就进行以下循环。

(1)令cur2.next指向cur3.next。

(2)设立临时变量temp存储cur1.next结点。令cur1.next节点指向cur3,即将待处理节点放在第一个节点的位置,而令cur3.next为temp。

(3)更新cur3的值为cur2.next。

最后我们返回翻转后的结果dummyHead.next即可。

时间复杂度是O(n)级别的,其中n为链表中的节点数。空间复杂度是O(1)级别的。

JAVA代码:

public class Solution {
  
  public ListNode reverseList(ListNode head) {
    ListNode dummyHead = new ListNode(-1);
    dummyHead.next = head;
    ListNode cur1 = dummyHead;
    if(cur1.next == null || cur1.next.next == null) {
      return head;
    }
    ListNode cur2 = cur1.next;
    ListNode cur3 = cur2.next;
    while(cur3 != null) {
      cur2.next = cur3.next;
      ListNode temp = cur1.next;
      cur1.next = cur3;
      cur3.next = temp;
      cur3 = cur2.next;
    }
    return dummyHead.next;
  }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-200题汇总,希望对你有点帮助!

LeetCode刷题实战201:数字范围按位与

LeetCode刷题实战202:快乐数

LeetCode刷题实战203:移除链表元素

LeetCode刷题实战204:计数质数

LeetCode刷题实战205:同构字符串

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值