k个一组翻转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
     
     Stack<ListNode> stack=new Stack<>();
    public ListNode reverseKGroup(ListNode head, int k) {
     
        if(k==1){
     
            return head;
        }
        ListNode node=head;
        stack.push(head);
        for(int i=1;i<k;i++){
     
            if(node==null||node.next==null){
     
                return head;
            }
            node=node.next;
            stack.push(node);
        }
         node=node.next;
        ListNode nh=stack.pop();
         ListNode p=nh;
         while (stack.size()>0){
     
            
             p.next=stack.pop();
            p=p.next;
        }
        p.next=reverseKGroup(node,k);
        return nh;
    }
}

你可能感兴趣的:(k个一组翻转链表)