K 个一组翻转链表

2020-07-28  本文已影响0人  dalewong

从最基础的翻转链表开始:

def reverse_linklist(l):
    prev = None
    head = l.head
    while head:
        tmp = head.next
        head.next = prev
        prev = head
        head = tmp

好,我们开始计算K个一组翻转列表:

  1. k个一组的数组翻转
  2. 组个组的之间的指针的指向修改
# coding: utf-8


class LinkListNode(object):

    def __init__(self, value):
        self.value = value
        self.next = None


def k_reverse_list(head, k):
    # 首先需要构造pre指针指向组
    pre = LinkListNode(None)
    pre.next = head
    # 需要一个固定的指针指向联表的头部, 最后好返回整个链表
    hair = pre
    while head:
        tail = head
        for i in range(k):
            # k个分组
            tail = tail.next
            if not tail:
                break
        # 设置lnext保存下一个k组
        lnext = tail.next
        # 翻转组内的数据
        rhead, rtail = reverse_group(head, tail)
        # 使得pre指针指向翻转后的组, 并且tail指向下一个组的开始节点
        # pre指针移动到tail, head指针移动到tail.next
        pre.next = rhead
        rtail.next = lnext
        pre = tail
        head = lnext
    return hair.next


def reverse_group(head, tail):
    # 翻转之后tail.next为pre
    # [A --> B --> C] --> [D --> E]
    # [C --> B --> A] --> [E --> D]
    pre = tail.next
    p = head
    while pre != p:
        t_next = p.next
        p.next = pre
        pre = p
        p = t_next
    return tail, head
上一篇下一篇

猜你喜欢

热点阅读