题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

遍历链表,使用一个列表存储每个节点,step表示已经遍历的个数,每遍历k个就对node_list[step-k:step]进行转置,最后将列表中的节点进行拼接即可

class Solution:
      def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
          # write code here
          if not head:
              return head
          node_list = []
          temp = head
          step = 0
          while temp:
              node_list.append(temp)
              step += 1
              if step%k == 0:
                  node_list[step-k:step] = reversed(node_list[step-k:step])
              temp = temp.next

          for i in range(1,len(node_list)):
              node_list[i-1].next = node_list[i]
          node_list[-1].next = None
          return node_list[0]
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务