跟着leedcode刷算法 -- 链表3

98 阅读1分钟

这是我参与11月更文挑战的第20天,活动详情查看:2021最后一次更文挑战

image.png

题5

反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。   示例 1:

image.png

  • 输入:head = [1,2,3,4,5]
  • 输出:[5,4,3,2,1] 示例 2:

image.png

  • 输入:head = [1,2]

  • 输出:[2,1] 示例 3:

  • 输入:head = []

  • 输出:[]  

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000  

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

相关标签

  • 递归
  • 链表

常用方法:递归方法进行开发

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
             return head
        
        res = self.reverseList(head.next) 
        head.next.next = head
        head.next = None
        
        return res

执行结果:

image.png

题6

回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

示例 1:

  • 输入:head = [1,2,2,1]

  • 输出:true 示例 2:

  • 输入:head = [1,2]

  • 输出:false  

提示:

  • 链表中节点数目在范围[1, 105] 内
  • 0 <= Node.val <= 9  

进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

相关标签

  • 递归
  • 链表
  • 双指针

使用一个最简单的思路:遍历链表的所有值然后判断res==res[::-1]

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        res = []
        node = head
        while node is not None:
            res.append(node.val)
            node = node.next
        return res == res[::-1]

执行结果:

image.png