• 1.8单链表以k个节点为一组翻转


    单链表以k个节点为一组进行翻转

    解题思路:

    首先把前K个结点看成一个子链表,采用前面介绍的方法进行翻转,把翻转后的子链表链接到头结点后面,然后把接下来的K个结点看成另外一个单独的链表进行翻转,把翻转后的子链表链接到上一个已经完成翻转子链表的后面

    图示:

    代码实现

    # -*-coding:utf-8-*- 
    """
    @Author  : 图南
    @Software: PyCharm
    @Time    : 2019/9/7 11:37
    """
    
    
    class Node:
        def __init__(self, data=None, next=None):
            self.data = data
            self.next = next
    
    
    def con_link(n):
        head = Node()
        cur = head
        for i in range(1, n + 1):
            node = Node(i)
            cur.next = node
            cur = node
        return head
    
    
    def print_link(head):
        if head is None or head.next is None:
            return
        cur = head.next
        while cur:
            print(cur.data, end=" ")
            cur = cur.next
        print()
    
    
    def reverseKNode(head, k):
        if head is None or head.next is None:
            return
        if k == 0 or k == 1:
            return head
        pre = head
        begin = head.next
        while begin:
            end = begin
            for i in range(k-1):
                if end.next:
                    end = end.next
                else:
                    return head
            next= end.next
            end.next = None
            r_head, r_end = reverseLink(begin)
            r_end.next = next
            pre.next = r_head
            pre = r_end
            begin = next
        return head
    
    
    
    
    def reverseLink(head):
        if head is None or head.next is None:
            return
        r_end = head
        pre = head
        r_head = pre.next
        pre.next = None
        while r_head.next:
            next = r_head.next
            r_head.next = pre
            pre = r_head
            r_head = next
        r_head.next = pre
        return r_head, r_end
    
    
    if __name__ == '__main__':
        n = int(input("请输入n:"))
        k = int(input("请输入k:"))
        head = con_link(n)
        print_link(head)
        head = reverseKNode(head, k)
        print_link(head)
    

    运行结果:



  • 相关阅读:
    中医手诊原理
    半月痕
    0020 教您新手修车的五种实用技巧
    下面说说我开车12年来的一些心得
    创建电子邮件信纸
    交通事故责任划分2011版(图解)
    育儿语录
    汽车中控台那些按钮是什么用的?
    我的书中的部分函数
    纠结的书名
  • 原文地址:https://www.cnblogs.com/miao-study/p/11480628.html
Copyright © 2020-2023  润新知