用栈做:
# 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 """ dummy=ListNode(0) p=dummy while True: count=k stack=[] tmp=head while count and tmp: stack.append(tmp) tmp=tmp.next count-=1 if count: p.next=head break while stack: p.next=stack.pop() p=p.next p.next=tmp head=tmp return dummy.next
执行用时 :32 ms, 在所有 python 提交中击败了95.97%的用户
内存消耗 :13.2 MB, 在所有 python 提交中击败了44.26%的用户
——2019.10.31
public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; ListNode end = dummy; while (end.next != null) { for (int i = 0; i < k && end != null; i++) end = end.next; if (end == null) break; ListNode start = pre.next; ListNode next = end.next; end.next = null; pre.next = reverse(start); start.next = next; pre = start; end = pre; } return dummy.next; } private ListNode reverse(ListNode head) { ListNode pre = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = pre; pre = curr; curr = next; } return pre; }
自己还是没能做出来。
——2020.7.14