字节跳动面试题,翻转链表,LeetCode 206、92、 25

字节跳动面试题,翻转链表,LeetCode 206 92 25

  • 题目
    • LeetCode 206
      • code
    • LeetCode 92
      • Code
    • LeetCode 25
      • Code
    • 字节跳动链表题
  • 欢迎一起来参与leetcode刷题项目

题目

最近在看面经,看到一个字节跳动的算法题,然后发现这题在leetcode里有原型,先由浅入深的写三道leetcode的题目,最后再看看原题。听说字节跳动必考链表题

LeetCode 206

这是一道超级简单的题目,很直接,翻转链表

1
2
3
4
5
NULL
5
4
3
2
1
NULL

code

我感觉代码很简单,先看看吧

calss Solution:
	def reverseList(self, head: ListNode) --> ListNode:
		if head is None:
			return None
		curr = head
		pre = None
		while curr:
			curr.next, pre, curr = pre, curr, curr.next
			# 这个逻辑
			# curr_next = curr.next
			# curr.next = pre
			# pre = curr
			# curr = curr_next
		return pre

LeetCode 92

这一题就是在206题目上加了一个小条件,不在是翻转整个链表,而是翻转,指定区间的链表,这个条件也没有多复杂,找到指定区间的前缀和后缀,然后再翻转指定区间,完成

Code

class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        if head is None:
            return None
        if not(m-n):
            return head
        l = 0
        pre_node, next_node, node = None, None, head
        while node:
            l += 1
            pre_node = node if l == m-1 else pre_node
            next_node = node if l == n+1 else next_node
            node = node.next
            
        if m<1 or n>l or m>n:
            return None
        node = pre_node.next if pre_node else head
        node2 = node.next
        node.next = next_node
        
        while not(node2 is next_node):
            nn = node2.next
            node2.next = node
            node = node2
            node2 = nn
        
        if pre_node:
            pre_node.next = node
            return head
        else:
            return node

现在我们已经知道怎么翻转整个链表,也知道如何翻转指定区间的链表,下面我们来看看,有多个区间怎么翻转,或者说,给定一个步长为k的滑窗,翻转滑窗内的链表

LeetCode 25

Code

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return None
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        
        def reverse(pre: ListNode, k: int) -> ListNode:
            last = pre
            for i in range(k+1):
                last = last.next
                if i != k and last is None:
                    return None
            # 对pre  和  last 中间的节点做reverse
            tail = pre.next
            curr = pre.next.next
            while curr != last:
                curr_next = curr.next
                curr.next = pre.next
                pre.next = curr
                tail.next = curr_next
                curr = curr_next
            #end_while
            return tail
        ###
        while pre:
            pre = reverse(pre, k)
        return dummy.next

字节跳动链表题

这题和LeetCode25很像,唯一不同的是它要求滑窗是从后向前移动,有人可能因为紧张没想通,因为单向链表求某个结点的前缀,(从头再遍历一遍呗,还能咋的)。但是你把它翻转一遍就变成LeetCode25,最后把答案再reverse一遍。

欢迎一起来参与leetcode刷题项目

刷题的GitHub: github链接.

你可能感兴趣的:(leetcode)