Skip to content

[LinkedList] 25. Reverse Nodes in k-Group K 个一组翻转链表 #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jotoy opened this issue Jan 27, 2020 · 0 comments
Open

[LinkedList] 25. Reverse Nodes in k-Group K 个一组翻转链表 #2

jotoy opened this issue Jan 27, 2020 · 0 comments

Comments

@jotoy
Copy link
Owner

jotoy commented Jan 27, 2020

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5

说明 :

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路:

本题与24题有些相似,需要构建快慢指针完成节点的交换。
由于本题需要将k个节点一组进行翻转,因此最好先通过链表的遍历,确定链表的长度。然后根据链表长度,将链表分为n等份。在每一份中进行局部的翻转,然后将指针指向局部外的节点,进行下一个局部的翻转。直到n等份全部翻转完成,返回头节点。

解法:

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if head == None or head.next == None:
            return head
        l = 1
        phead = head
        while phead.next:
            phead = phead.next
            l += 1
        p = ListNode(None)
        p.next = head
        pre = p
        cur = p
        while l>=k:
            cur = pre.next # 1-2-3
            for _ in range(k-1):
                next = cur.next  # 2-3-4 
                cur.next = next.next # 1-3-4
                next.next = pre.next # 2-1-3-4
                pre.next = next  # None-2-1
            pre = cur
            l -= k 
        return p.next
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant