• 链表_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)


  • 相关阅读:
    【算法】数据结构
    【POJ】1222 EXTENDED LIGHTS OUT
    【BZOJ】1013 [JSOI2008]球形空间产生器sphere
    【有上下界网络流】【ZOJ】2314 Reactor Cooling
    【CODEVS】1281 Xn数列
    【POJ】3070 Fibonacci
    【CODEVS】3546 矩阵链乘法
    【BZOJ】1070: [SCOI2007]修车
    Quoit Design(hdu 1007)
    tree(poj 1741)
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10557132.html
Copyright © 2020-2023  润新知