leetcode:Reverse Nodes in k-Group

来源:互联网 发布:任子行 知乎 编辑:程序博客网 时间:2024/06/06 13:02

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5




/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if(head != null && k > 1){            int len = getLen(head);            int remain = len % k;            int groups = len / k;                        ListNode next = null;            ListNode pre = head;            ListNode tail = head;            ListNode preTail = null;            for(int i = 0; i < groups; ++i){                tail =  pre;                for(int j = 0; j < k; ++j){                    ListNode temp =pre.next;                    pre.next = next;                    next= pre;                    pre = temp;                }                if(tail == head){                    head = next;                }                if(preTail != null){                    preTail.next = next;                }                preTail = tail;                            }            if(preTail != null){                preTail.next = pre;            }        }        return head;    }        public int getLen(ListNode list){        int len = 0;        while(list != null){            ++len;            list = list.next;        }        return len;    }}


0 0