zoukankan      html  css  js  c++  java
  • 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)
    

    运行结果:



  • 相关阅读:
    JSON.parse()和JSON.stringify()
    MySql 只能访问localhost 和 127.0.0.1访问 不能通过其他IP访问
    JavaScript 严格模式
    设计模式学习--单例模式
    golang 读写文件(一)
    eclipse 快捷键收藏
    Swift网络封装库Moya中文手册之Authentication
    Swift网络封装库Moya中文手册之Endpoints
    Swift网络封装库Moya中文手册之Plugins
    Swift网络封装库Moya中文手册之Providers
  • 原文地址:https://www.cnblogs.com/miao-study/p/11480628.html
Copyright © 2011-2022 走看看