zoukankan      html  css  js  c++  java
  • 链表_leetcode25

    # Definition for singly-linked list.
    class ListNode(object):
    def __init__(self, x):
    self.val = x
    self.next = None

    class Solution(object):
    def reverseKGroup(self, head, k):
    """
    :type head: ListNode
    :type k: int
    :rtype: ListNode
    """

    dummyHead = ListNode(0)

    dummyHead.next = head

    pre = dummyHead
    fNode = head

    kNode = self.hasKNode(fNode,k)


    # self.reverseKList(pre,fNode,kNode,k)
    #
    #
    # self.printList(dummyHead.next)

    # pre = fNode
    # fNode = pre.next
    # kNode = self.hasKNode(fNode,k)
    #
    # print kNode.val
    #
    # self.reverseKList(pre, fNode, kNode, k)
    # self.printList(dummyHead.next)

    while kNode:

    self.reverseKList(pre,fNode,kNode,k)
    pre = fNode
    fNode = pre.next
    kNode = self.hasKNode(fNode,k)



    return dummyHead.next


    def hasKNode(self,head,k):

    count = 1
    cur = head

    while cur and count < k:
    cur = cur.next
    count += 1

    if cur:
    return cur
    else :
    return None

    def reverseKList(self,pre,fNode,Knode,k):

    curNode = fNode.next
    nextKnode = Knode.next
    fNode.next = nextKnode

    # while curNode != nextKnode:
    # curNode.next = pre.next
    # pre.next = curNode
    # curNode = curNode.next

    for i in range(k-1):
    nextCur = curNode.next
    curNode.next = pre.next
    pre.next = curNode
    curNode = nextCur



    def creatList(self,l):
    dummyHead = ListNode(0)

    pre = dummyHead

    for i in l:
    pre.next = ListNode(i)
    pre = pre.next

    return dummyHead.next


    def printList(self,head):
    cur = head

    while cur:
    print cur.val
    cur = cur.next



    l1 = [1,2,3,4,5]

    s = Solution()

    head = s.creatList(l1)

    s.printList(head)

    head = s.reverseKGroup(head,3)
    #
    s.printList(head)


  • 相关阅读:
    Virtuabox 虚拟机克隆方法
    CentOS 7 防火墙 出现Failed to start iptables.service: Unit iptables.service failed to load
    Linux系统下安装rz/sz命令及使用说明
    os、sys模块
    collections、random、hashlib、configparser、logging模块
    time、datatime模块
    正则表达式、re模块
    递归、二分查找法
    内置函数、匿名函数
    生成器进阶、生成器表达式
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557132.html
Copyright © 2011-2022 走看看