fucking algorithm - 迭代反转链表

迭代可以 o(1) 的空间复杂度,o(n) 的时间复杂度,翻转链表。

k个一组翻转链表:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

 

还是可以看做递归问题,每次返回的是新的head,通过 head.next 递归调用下一个翻转组。

base case 就是停下来的时候,在本题中就是不足 k个的一组。

 

首先考虑迭代翻转整个链表

def reverseList(head):

     tail = None

     while head.next is not None:

    tmp = head.next

    head.next = tail

    tail = head

    head = tmp

  return head

 

反转整个链表 = 反转 a 到 null 的节点。

所以也会了反转 a 到 b 的节点。

 

def reverseList(head, b):  // 左闭右开!

  newHead = None

      cur = head

      while cur != b:

    tmp = cur.next

    cur.next = newHead

    newHead = cur

    cur = tmp

  return newHead

 

 

 

 

那么 reverseKGroup 就是先遍历 k 个,如果不足 k 个直接返回即可。

 

posted @ 2021-04-12 22:54  nuo-o  阅读(70)  评论(0编辑  收藏  举报