The method uses stack which will give you another idea.NO PASS.ATTENTION PLEASE!


  • 0
    X

    public class Solution {
    public ListNode reverseKGroup(ListNode head,int k) {
    if(head == null || head.next==null)
    return head;
    else{
    ListNode dum=new ListNode(0);
    ListNode head2=head;
    dum.next=head2;
    int count=0;
    while(head2!=null)
    {
    count++;
    head2=head2.next;
    }
    if(k>count)
    return dum.next;
    else
    {
    Stack<ListNode> stack=new Stack<ListNode>();
    ListNode dummy=new ListNode(0);
    ListNode open=new ListNode(0);
    dummy.next=open;
    open.next=head;
    int num=k;
    while(num<=count)
    {
    for(int i=0;i<k;i++)
    {
    stack.push(head);
    head=head.next;
    }
    while(stack.size()>0)
    {
    open.next=stack.pop();
    open=open.next;
    }
    num+=k;
    }
    if(head!=null)
    open.next=head;
    return dummy.next.next;
    }
    }
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.