• 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)
    

    运行结果:



  • 相关阅读:
    通用爬虫和聚焦爬虫
    分布式缓存的介绍
    点击按钮执行后台方法
    jsp页面设置绝对路径
    vim调试
    图解Java 垃圾回收机制
    Java String 综述(上篇)
    Java 内部类综述
    深入理解Java类加载器(二):线程上下文类加载器
    深入理解Java类加载器(一):Java类加载原理解析
  • 原文地址:https://www.cnblogs.com/miao-study/p/11480628.html
Copyright © 2020-2023  润新知