leetcode Reverse Nodes in k-Group

来源:互联网 发布:linux强制退出不保存 编辑:程序博客网 时间:2024/06/05 22:52

题目链接

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {     public ListNode reverseKGroup(ListNode head, int k) {        ListNode newHead=new ListNode(1);        ListNode result=newHead;        ListNode pointer=head;        while(pointer!=null)        {            ListNode end=pointer;            for(int i=1;i<k&&end!=null;i++)            {                end=end.next;            }            if(end==null)            {                newHead.next=pointer;                break;            }            ListNode nextPoin=end.next;            end.next=null;            newHead.next=reverse(pointer);            newHead=pointer;            pointer=nextPoin;        }        return result.next;    }    public ListNode reverse(ListNode toReverse)    {        ListNode result=null;        while(toReverse!=null)        {            ListNode temp=toReverse.next;            toReverse.next=result;            result=toReverse;            toReverse=temp;        }        return result;    }}
0 0